您的位置:首页 > 其它

LeetCode——016

2016-04-16 09:23 288 查看


/*

16. 3Sum Closest My Submissions QuestionEditorial Solution

Total Accepted: 74474 Total Submissions: 257407 Difficulty: Medium

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).


Subscribe to see which companies asked this question

*/

/*

解题思路:

与上一题一样还是采用定一议二策略

要找最相近的和值,比较的应该是距离即差的绝对值。但是在选后两个数的时候还是根据自然差值进行移动left或right 。特殊情况如和直接等于target,那么就直接返回0,因为没有比这更近的了。

本题在遍历的时候只是在确定第一个数的时候 采用了去重(即如果上一个数与当前数相等则忽略过去),但在寻找后两个数的时候,这个忽略操作不做也可以通过oj。

在设定res的初始值时要注意直接用nums[0]+nums[1]+nums[2], 我一开始用了INT_MAX发现不对,原因就是当target为负数时 res-target会超出整数的范围。

*/

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

int res;
sort(nums.begin(),nums.end());

if(nums.size()<3)return -1;
res=nums[0]+nums[1]+nums[2];
for(int i=0;i<nums.size()-2;i++){

if(i==0|| (i>0 && nums[i]!=nums[i-1])){
int left=i+1,right=nums.size()-1;
while(left<right){

int val=nums[left]+nums[right]+nums[i];
if(val-target==0)return target;
if(abs(val-target)<abs(res-target))res=val;
if(val-target<0)++left;
else --right;
}
}
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: