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).Thoughts:
add a distance tracking variable and update its value after each two-sum search. Other than this, the implementation is based on standard 3sum.
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size(), ans = INT_MAX, distance = INT_MAX;
sort(nums.begin(),nums.end());
for (int i = 0; i < len; i++){
int left = i + 1, right = len - 1;
while(left < right){
int sum = nums[left] + nums[right] + nums[i];
if (sum == target){
return sum;
}
else if (sum < target){
update(ans, distance , sum, target);
left ++;
}
else {
update(ans, distance, sum, target);
right --;
}
}
}
return ans;
}
void update(int& ans, int& distance, int sum, int target){
int curDistance = sum > target? sum - target: target - sum;
ans = distance > curDistance? sum : ans;
distance = distance > curDistance? curDistance : distance;
}
};Extension: I can also calculate the minimum distance two-sum distance for current target and keep track the corresponding 3sum value in my answer as the following:
I can also update them in the loop, as 水中的鱼's approach in this problem.
Last updated
Was this helpful?