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).
這道題一開(kāi)始我把是固定left和right咏连,然后讓i在中間循環(huán)蒸眠,后來(lái)發(fā)現(xiàn)越來(lái)越混亂。之后看了答案版确,答案是先循環(huán)i, 然后用two pointers讓left和right左右移動(dòng),就顯得簡(jiǎn)單很多畦娄。
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int minDiff = Integer.MAX_VALUE;
int closestSum = 0;
for (int i = 0; i < nums.length; i++){
int left = i + 1;
int right = nums.length - 1;
while (left < right){
int sum = nums[i] + nums[left] + nums[right];
int diff = Math.abs(target - sum);
if (diff < minDiff){
minDiff = diff;
closestSum = sum;
}
if (sum < target){
left++;
} else {
right--;
}
}
}
return closestSum;
}
}