题目大意:与15题类似,只是这里求的不是三个数之和等于target,而是三个数之和最接近target。
法一(借鉴):记录与target相差的绝对值最小值,然后更新记录。先排序,两层循环,外层循环遍历取一个数,内层循环两指针找合适的值。代码如下(耗时13ms):
1 public int threeSumClosest(int[] nums, int target) { 2 Arrays.sort(nums); 3 int sum = 0, res = 0, diff = 0, mi = Integer.MAX_VALUE; 4 for(int i = 0; i < nums.length - 2; i++) { 5 int left = i + 1, right = nums.length - 1; 6 while(left < right) { 7 sum = nums[i] + nums[left] + nums[right]; 8 diff = Math.abs(sum - target); 9 if(diff < mi) { 10 mi = diff; 11 res = sum; 12 } 13 if(sum < target) { 14 left++; 15 } 16 else { 17 right--; 18 } 19 } 20 } 21 return res; 22 }