LeetCode 16 – 3Sum Closest

Posted on December 25, 2013

Last updated on December 25, 2013

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;
}
3Sum Closest
Markdown SHA1: cf56b69744b9c441914a2804b9fd6dcbc5d74a56