3Sum Closest
Problem
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
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
int res = nums[0] + nums[1] + nums[2]; //cannot just init res with 0 (int res = 0 is wrong!)
for (int i = 0; i < len - 2; i++) {
int left = i + 1, right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (Math.abs(target - sum) < Math.abs(target - res)) res = sum;
if (sum < target) left++;
else if (sum > target) right--;
else return sum; //Optimize the algorithm by terminating earlier
}
}
return res;
}
}
Analysis
The idea is loop through all possible sums and update the result if we find a closer sum to target
We use Binary Search to optimize our algorithm
We have the current number nums[i]
, left-most number nums[i+1]
, and right-most number nums[len - 1]
Notice that we need to handle with some corner cases before we start the binary search
Complexity:
- Time: O(n^2), in worst case we have to go through the for and while statement completely
- Space: O(n), only constant space is used