Leetcode#16 3Sum Cloest
Published:
Link:
https://leetcode.com/problems/3sum-closest/description/
Idea:
Same as 3Sum, record minimum gap.
Solution:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if (nums.size() < 3)
return 0;
sort(nums.begin(), nums.end());
int gap = INT_MAX;
for(int i=0; i<nums.size(); i++) {
if (i>0 && nums[i] == nums[i-1])
continue;
int tmp = target - nums[i];
int left = i+1;
int right = nums.size()-1;
while (left < right) {
int diff = tmp - (nums[left] + nums[right]);
if (abs(diff) < abs(gap)) {
gap = diff;
}
if(diff == 0) {
return target;
} else {
if (diff < 0) {
right--;
} else {
left++;
}
}
}
}
return target - gap;
}
};