Description:
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.
Solution:
This problem is similar to the former one, but with slightly different.
This problem just asks us to calculate the closest number, which means we need to calculate every three number unless the three has been in the queue before. And in the 3Sum problem, one of the important optimizations is that once three number sum is 0, at most two sum is the same, both positive/negative, while the last one should be the opposite, that is negative/positive.
But this optimization under this circumstances is quite different. Because we want to find out the closest one, so no guarantee the three number should be obey.
In addition to this one, we can get the answer in simple way: for each number in the array, we start from the sum from rightmost and leftmost, then when the sum is smaller than target, leftmost index++; if greater, rightmost index--; if they are the same, then straightly return this sum.
import java.util.Arrays;
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int min = 2 << 20 - target, ans = 0;
int l, r, temp;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
l = i + 1;
r = nums.length - 1;
while (l < r) {
temp = nums[i] + nums[l] + nums[r];
if (temp == target) {
return target;
} else if (temp < target) {
l++;
if (min > target - temp) {
min = target - temp;
ans = temp;
}
} else {
r--;
if (min > temp - target) {
min = temp - target;
ans = temp;
}
}
// System.out.println("after " + temp + " " + (target + min)
// + " " + (target - min) + " " + min);
}
}
return ans;
}
public static void main(String[] args) {
int[] arr = { 0, 0, 0 };
int a = 1;
Solution s = new Solution();
System.out.println(s.threeSumClosest(arr, a));
}
}