題目
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 個整數(shù)的數(shù)組 S, 找到和與給定整數(shù) target 最接近的三元組鳍贾,返回這三個數(shù)的和。
樣例
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這道題相似骑科,這里的時間復(fù)雜度仍然是O(n^2)。
分別使用3個指針來指向當(dāng)前元素构拳、下一個元素和最后一個元素咆爽。如果結(jié)果Sum是小于目標(biāo)值的,我們就將下一個元素接著向數(shù)組右側(cè)遍歷隐圾;如果結(jié)果Sum是大于目標(biāo)值的伍掀,那么我們將最后一個元素向左側(cè)遍歷掰茶。
并且暇藏,每次我們都比較當(dāng)前結(jié)果和目標(biāo)值的差值,如果這個差值小于上一次的結(jié)果濒蒋,將上一次的結(jié)果替換盐碱,否則的話,繼續(xù)遍歷沪伙。
具體代碼如下:
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;
}