您的位置:首页 > 其它

3Sum Closest

2015-08-26 10:32 169 查看
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.

思路:这道题目的做法与3Sum的做法大致相同,只不过需要增加一个标记来记录每一次比较的最接近的值即可,代码如下:

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size(), i, j, k, closest = 0, delta = 2147483647;
if(len == 3)
return nums[0] + nums[1] +nums[2];
sort(nums.begin(), nums.end());
for(i = 0; i < len - 2; ++i){
if(i > 0 && nums[i] == nums[i - 1])
continue;
j = i + 1;
k = len - 1;
while(j < k){
if(j > i + 1 && nums[j] == nums[j - 1]){
j++;
continue;
}
if(k < len - 1 && nums[k] == nums[k + 1]){
k--;
continue;
}
int sum = nums[i] + nums[j] + nums[k];
int tmpDelta = abs(sum-target);
if(delta > tmpDelta){
delta = tmpDelta;
closest = sum;
}
if(sum < target)
j ++;
else if(sum > target)
k --;
else{
return sum;
}
}
}
return closest;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: