16. 3Sum Closest java solutions

Posted Miller1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了16. 3Sum Closest java solutions相关的知识,希望对你有一定的参考价值。

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

 

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public int threeSumClosest(int[] nums, int target) {
 3         int ans = 0,min = Integer.MAX_VALUE;
 4         Arrays.sort(nums);
 5         for(int i = 0; i < nums.length-2; i++){
 6             if(i > 0 && nums[i] == nums[i-1])
 7                 continue;
 8             for(int s = i + 1,e = nums.length-1;s < e;){
 9                 int sum = nums[i] + nums[s] + nums[e];
10                 if(Math.abs(sum - target) < min){
11                     min = Math.abs(sum-target);
12                     ans = sum;
13                 }
14                 if(sum > target) e--;
15                 else if(sum < target) s++;
16                 else return ans;
17             }
18         }
19         return ans;
20     }
21 }

 

以上是关于16. 3Sum Closest java solutions的主要内容,如果未能解决你的问题,请参考以下文章

java 16. 3Sum Closest(#)。java

java 16. 3Sum Closest(#)。java

java 16. 3Sum Closest(#)。java

java 16. 3Sum Closest(#)。java

16. 3Sum Closest java solutions

16. 3Sum Closest