3Sum Closest
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).
解析
在数组中找三个数之和,让其与target最相近,返回这个和。
同3Sum的解法,先对数组排序,然后依次固定一个数,再用两个指针遍历后面的数,找到三个数之和最相近的三个数之和。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int size = nums.size();
sort(nums.begin(),nums.end());
int closesum = nums[0]+nums[1]+nums[2];
int diff = abs(target-closesum);
for(int i=0;i<size-2;i++){
int left =i+1,right=size-1;
while(left<right){
int sum = nums[i]+nums[left]+nums[right];
int newdiff = abs(target-sum);
if(newdiff < diff){
closesum = sum;
diff = newdiff;
}
if(sum < target)
left ++;
else
right--;
}
}
return closesum;
}
};