[leetcode]16. 3Sum Closest
Analysis
fighting—— [每天刷题并不难0.0]
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Explanation:
Detailed explanation:
https://leetcode.com/problems/3sum-closest/discuss/7883/C%2B%2B-solution-O(n2)-using-sort
Implement
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size();
if(len < 3)
return 0;
int closest = nums[0]+nums[1]+nums[2];
sort(nums.begin(), nums.end());
for(int i1=0; i1<len-2; i1++){
if(i1>0 && nums[i1] == nums[i1-1])
continue;
int i2 = i1+1;
int i3 = len-1;
while(i2 < i3){
int cur = nums[i1]+nums[i2]+nums[i3];
if(cur == target)
return cur;
if(abs(cur-target) < abs(closest-target))
closest = cur;
if(cur < target)
i2++;
else
i3--;
}
}
return closest;
}
};