16. 3Sum Closest
Description
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.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Analysis
方法大致与15. 3Sum相同,只是要设一个表示target和当前三个数字之差的min值,不断更新min,同时将三数字之和赋值给返回值res。
不明白注释掉的两个while循环为啥写上就不对了…
Code
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = nums[0]+nums[1]+nums[2];
int min = abs(nums[0]+nums[1]+nums[2]-target);
if(min==0)
return target;
sort(nums.begin(), nums.end());
for(int i=0; i<nums.size()-2; i++){
int front = i+1;
int back = nums.size()-1;
while(front<back){
int sum = nums[i]+nums[front]+nums[back];
if(sum==target)
return target;
if(abs(sum-target)<min){
min = abs(sum-target);
res = sum;
int minfront = front;
int minback = back;
// while(front<back && nums[front]==nums[minfront])
// front++;
// while(front<back && nums[back]==nums[minback])
// back--;
}
else{
if(sum<target){
front++;
}
else if(sum>target){
back--;
}
}
}
while(i+1<nums.size() && nums[i+1]==nums[i])
i++;
}
return res;
}
};