16.3 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:
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;
int curTarget = target - nums[i]; //change 1: find the current target
while(left < right){
int sum = nums[left] + nums[right];
if (sum == curTarget){ // change 2:
return target;
}
else if (sum < curTarget){
update(ans, distance , sum, curTarget, nums[i]); // change 3: (important): pass in an extra arguement for updating ans
left ++;
}
else {
update(ans, distance, sum, curTarget, nums[i]); // change 3 (important): pass in an extra arguement for updating ans
right --;
}
}
}
return ans;
}
void update(int& ans, int& distance, int sum, int target, int base){
int curDistance = sum > target? sum - target: target - sum;
ans = distance > curDistance? sum + base : ans; // change 4: the candidate for new ans is "sum + base"
distance = distance > curDistance? curDistance : distance;
}
};
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
ans, dist = sys.maxint, sys.maxint #(sum(abs(nums))) - target
n = len(nums)
for i in range(n - 1):
j, k = i + 1, n - 1
while j < k:
s = nums[i] + nums[j] + nums[k]
if s == target:
return s
elif s < target:
j += 1
else: # s > target:
k -= 1
tmp = dist
dist = min(abs(s - target), dist)
ans = ans if dist == tmp else s
return ans
I can also update them in the loop, as 水中的鱼's approach in this problem.