Solution to LeetCode 3Sum Closest problem.
The idea is the same as in the 3SUM question. Sort the array, and in \(O(n^2)\) time find the closest value.
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int minDiff = Integer.MAX_VALUE;
int bestSum = 0;
for(int i = 0; i < num.length-2; i++){
int j = i+1;
int k = num.length-1;
while(j < k){
int sum = num[i] + num[j] + num[k];
if(Math.abs(sum-target) < minDiff){
minDiff = Math.abs(sum-target);
bestSum = sum;
}
if(sum > target) k--;
else j++;
}
}
return bestSum;
}