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
给出一个数组,一个target数字,让找出3个数字的和,使得这个和与target最接近
每个数组都有一个解
思路:
涉及到3 Sum的问题,还是用3 Sum的思路,选一个数字,剩下的用2 Sum,以解决遍历所有和的问题
与target最接近表示|sum - target| 越小,注意这个是绝对值的差,所以要用一个变量保存最小的绝对值差,当一个更小的绝对值差出现时,就更新最小绝对值的差,并保存当前3个数字的和
先把数组排序,2 Sum就可以用双指针解决
2 Sum部分用双指针的话,只凭绝对值的差不能判断移动左指针还是右指针,所以移动指针的时候要用3个数字的和与target比较
注意遍历第一个数字的时候只需遍历到数组长度-2,因为保证后面还有至少两个数字
public int threeSumClosest(int[] nums, int target) {
if(nums == null || nums.length < 3) {
return -1;
}
int result = nums[0] + nums[1] + nums[2];
int diff = Math.abs(target - result);
int n = nums.length;
Arrays.sort(nums);
for(int i = 0; i < n-2; i ++) {
int left = i + 1;
int right = n - 1;
while(left < right) {
int sum = nums[i] + nums[left] + nums[right];
int newDiff = Math.abs(sum - target);
if(newDiff == 0) {
return target;
} else if(newDiff < diff) {
diff = newDiff;
result = sum;
}
if(sum < target) {
left ++;
} else {
right --;
}
}
}
return result;
}