16 3Sum Closest
链接:https://leetcode.com/problems/3sum-closest/
问题描述:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
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).
Hide Tags Array Two Pointers
Hide Similar Problems (M) 3Sum
问题和3 sum类似http://blog.csdn.net/efergrehbtrj/article/details/46855331。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int p1,p2;
int min=INT_MAX;
int result=0;
sort(nums.begin(),nums.end());
for(int i=0;i<(int)nums.size()-2;i++)
{
if(i > 0 && nums[i]==nums[i-1])
continue;
p1=i+1;
p2=nums.size()-1;
while(p1<p2)
{
if(p1>i+1&&nums[p1]==nums[p1-1])
{
p1++;
continue;
}
else if(p2<nums.size()-1&& nums[p2]==nums[p2+1])
{
p2--;
continue;
}
else if(abs(nums[i]+nums[p1]+nums[p2]-target)<min)
{
min=abs(nums[i]+nums[p1]+nums[p2]-target);
result=nums[i]+nums[p1]+nums[p2];
}
else if(nums[i]+nums[p1]+nums[p2]<target)
p1++;
else
p2--;
}
}
return result;
}
};