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的数即可。重要的是判断逻辑的思路。代码如下:
1 public int threeSumClosest(int[] nums, int target) { 2 if (nums == null || nums.length < 3) { 3 return 0; 4 } 5 6 Arrays.sort(nums); 7 8 int closest = nums[0]+nums[1]+nums[2] ; 9 10 for(int i = 0 ; i < nums.length-2 ; i++){ 11 int l = i+1 ; 12 int r = nums.length-1 ; 13 while(l < r){ 14 int sum = nums[i] + nums[l] + nums[r] ; 15 if(sum == target){ 16 return sum ; 17 }else if(sum < target){ 18 /* 19 * 三种情况: 20 * 1、closest < sum < target --->closest = sum 21 * 2、sum < target < closest --->| target-sum < closest-target ---> closest = sum 22 * | target-sum >= closest-target --> closest不变 23 * 3、sum <= closest <= target ---> closest不变 24 */ 25 if(sum > closest){ 26 //情况1 27 closest = sum ; 28 }else if(closest > target){ 29 //情况2 30 if(target-sum < closest-target){ 31 //情况2.1, 32 closest = sum ; 33 } 34 //情况2.2不用变化 35 } 36 //情况3不同变化 37 l++ ; 38 }else{ 39 //分析同上 40 if(sum < closest){ 41 closest = sum ; 42 }else if(closest < target){ 43 if(sum-target <= target-closest){ 44 closest = sum ; 45 } 46 } 47 r-- ; 48 } 49 } 50 51 } 52 return closest ; 53 }
时间: 2024-10-27 05:34:58