您的位置:首页 > 其它

3Sum Closest

2016-05-16 14:31 330 查看
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).

描述:给定一个数组和一个目标值target。求在数组中存在3个数的和最接近target

解决思路:初始化res=nums[0]+nums[1+nums[2],而后对于每个nums[i],执行下列过程

(1)for i from 0 to nums.size()-3。每个nums[i],其实start=i+1,end=nums.size()-1,求tmp=nums[i]+nums[start]+nums[end]的和

(2)如果abs(tmp-target)<abs(res-target),则说明tmp比res更接近target,更新res。

(3)如果tmp==target,则直接返回。否则if tmp>target--->end--;else tmp<target--->start++,这样是的tmp和target更接近。

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {

int len=nums.size();
sort(nums.begin(),nums.end());//sort the nums
int res=nums[0]+nums[1]+nums[2];//init
int sum_tmp;//保存临时和
int left,right;
for(int i=0;i<len-2;i++)
{
left=i+1;
right=len-1;
while(left<right)
{
sum_tmp=nums[i]+nums[left]+nums[right];
if(abs(sum_tmp-target)<abs(res-target))
res=sum_tmp;
if(sum_tmp<target)
left++;
else if(sum_tmp>target)
right--;
else
return target;
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: