題目
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.
給一個包含 n 個整數的數組 S, 找到和與給定整數 target 最接近的三元組,返回這三個數的和。
樣例
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).
例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元組是 -1 + 2 + 1 = 2.
解題思路
這道題的仍然是使用兩個指針 Two Pointers的方法來解決,解題思路和3 Sum這道題相似,這里的時間復雜度仍然是O(n^2)。
分別使用3個指針來指向當前元素、下一個元素和最后一個元素。如果結果Sum是小于目標值的,我們就將下一個元素接著向數組右側遍歷;如果結果Sum是大于目標值的,那么我們將最后一個元素向左側遍歷。
并且,每次我們都比較當前結果和目標值的差值,如果這個差值小于上一次的結果,將上一次的結果替換,否則的話,繼續遍歷。
具體代碼如下:
public int threeSumClosest(int[] nums, int target) {
int res = nums[0] + nums[1] + nums[nums.length - 1];
Arrays.sort(nums);
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];
if (sum == target) {
res = sum;
return res;
} else if (sum < target) {
left++;
} else {
right--;
}
if (Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
}
}
return res;
}