16. 3Sum Closest
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).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;
}
};Last updated
Was this helpful?