Question
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.
Example
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).
Solution
Similar with 3 Sum. Time complexity is O(n2)
public class Solution {
public int threeSumClosest(int[] numbers ,int target) {
int length = numbers.length;
Arrays.sort(numbers);
int min = Integer.MAX_VALUE;
int result = numbers[0] + numbers[1] + numbers[2];
for (int i = 0; i < length - 2; i++) {
if (i > 0 && numbers[i] == numbers[i - 1])
continue;
int l = i + 1, r = length - 1;
while (l < r) {
while (l < r && numbers[l] == numbers[l + 1])
l++;
while (l < r && numbers[r] == numbers[r - 1])
r--;
int sum = numbers[i] + numbers[l] + numbers[r];
if (sum > target)
r--;
else if (sum < target)
l++;
else
return target;
int tmp = Math.abs(sum - target);
if (tmp < min) {
min = tmp;
result = sum;
}
}
}
return result;
}
}