16. 3Sum Closest
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.
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 to 3Sum two pointers solution.
- Sort the array
- Initialize three indexes i, j, k, where i traverse from 0 to the end, j starts from i + 1 position to k k starts from the end of the array to j
- Calculate the sum, and difference
if get the smallest difference, update the so far closest value and difference value.
if sum > target : k--
< target : j++ = target : return target
- $$O(n^2)$$
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int diff = Integer.MAX_VALUE;
int res = 0;
for(int i = 0; i < nums.length; i++){
int j = i + 1;
int k = nums.length - 1;
while(k > j){
int sum = nums[i] + nums[j] + nums[k];
int curr_diff = Math.abs(nums[i] + nums[j] + nums[k] - target);
if(curr_diff < diff){
res = sum;
diff = curr_diff;
}
if(sum == target){
return target;
}else if (sum < target){
j++;
}else{
k--;
}
}
}
return res;
}
}