您的位置:首页 > 其它

16. 3Sum Closest

2016-07-22 16:18 323 查看
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).


只用返回最接近的和,没有具体数字,也没有下标要求,还只有唯一确定解,真是不错的条件。

但其实跟之前的一样,也是只需要找出不同的值来就行了。

int threeSumClosest(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(), nums.end());
int i, temp_sum = 0, sum = nums[0] + nums[1] + nums[2];
// sum初始化不能给定0之类的,否则会干扰判断,必须是实际存在的组合求和
for (i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int start = i + 1;
int end = nums.size() - 1;
while (start < end) {
temp_sum = nums[i] + nums[start] + nums[end];
if (abs(temp_sum - target) < abs(sum - target))
sum = temp_sum;
if (temp_sum == target) {
return sum;
}
else {
if (temp_sum < target) start++;
else
end--;
}
}
}
return sum;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: