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)
1 public class Solution { 2 public int threeSumClosest(int[] numbers ,int target) { 3 int length = numbers.length; 4 Arrays.sort(numbers); 5 int min = Integer.MAX_VALUE; 6 int result = numbers[0] + numbers[1] + numbers[2]; 7 for (int i = 0; i < length - 2; i++) { 8 if (i > 0 && numbers[i] == numbers[i - 1]) 9 continue; 10 int l = i + 1, r = length - 1; 11 while (l < r) { 12 while (l < r && numbers[l] == numbers[l + 1]) 13 l++; 14 while (l < r && numbers[r] == numbers[r - 1]) 15 r--; 16 int sum = numbers[i] + numbers[l] + numbers[r]; 17 if (sum > target) 18 r--; 19 else if (sum < target) 20 l++; 21 else 22 return target; 23 int tmp = Math.abs(sum - target); 24 if (tmp < min) { 25 min = tmp; 26 result = sum; 27 } 28 } 29 } 30 return result; 31 } 32 }