16. 3Sum Closest
Medium
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
解法:
继续套用3 Sum的解法并稍加改造即可。即,对数组排序并遍历,每个值都作为Closest集合中的一个值进行尝试。那么在a值固定的情况下,分别将数组其余部分的首部和尾部作为b和c的值,并和a累加起来。如果sum>target,则说明c的值过大,需要左移一位(尝试稍小点的);如果sum<target,说明b值过小,需要右移一位(尝试稍大点的值);如果sum == target,则说明恰巧找到了三个数,其和为target,那么直接返回target数值就好。在每次求和并与target比较时,将当前sum和target的差值绝对值与当前记录的最小值diff的绝对值相比较;如果abs(sum-target) < abs(diff),那么说明找到了比之前更贴近target的组合。这样反复以上步骤,直到数组中的每个值都作为a尝试了一遍以后,最终的结果就是target与diff的差值。
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums) ;
int diff = Integer.MAX_VALUE ;
for(int i=0; i<nums.length && diff !=0 ; i++){
int left = i+1 ;
int right = nums.length - 1 ;
while(left < right){
int sum = nums[i] + nums[left] + nums[right] ;
int curr_abs_diff = Math.abs(target - sum) ;
if(curr_abs_diff < Math.abs(diff)){
diff = target - sum ;
}
if(sum < target){
left ++ ;
} else {
right -- ;
}
}
}
return target - diff ;
}