No.016 3Sum Closest

16. 3Sum Closest

  • Total Accepted: 86565
  • Total Submissions: 291260
  • Difficulty: Medium

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).

 思路:

  本题的解法和上一次3Sum的解法有点类似,我们可以先将数组排序,然后将数组中的数从左到右依次确定为第一个数,在其右边的数中寻找最接近的target的数即可。重要的是判断逻辑的思路。代码如下:

 public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3) {
return 0;
} Arrays.sort(nums); int closest = nums[0]+nums[1]+nums[2] ; for(int i = 0 ; i < nums.length-2 ; i++){
int l = i+1 ;
int r = nums.length-1 ;
while(l < r){
int sum = nums[i] + nums[l] + nums[r] ;
if(sum == target){
return sum ;
}else if(sum < target){
/*
* 三种情况:
* 1、closest < sum < target --->closest = sum
* 2、sum < target < closest --->| target-sum < closest-target ---> closest = sum
* | target-sum >= closest-target --> closest不变
* 3、sum <= closest <= target ---> closest不变
*/
if(sum > closest){
//情况1
closest = sum ;
}else if(closest > target){
//情况2
if(target-sum < closest-target){
//情况2.1,
closest = sum ;
}
//情况2.2不用变化
}
//情况3不同变化
l++ ;
}else{
//分析同上
if(sum < closest){
closest = sum ;
}else if(closest < target){
if(sum-target <= target-closest){
closest = sum ;
}
}
r-- ;
}
} }
return closest ;
}
上一篇:[No00005C]我也入住Markdown


下一篇:python,栈的小例子