您的位置:首页 > 编程语言 > C语言/C++

LeetCode刷题(C++)——3Sum Closest(Medium)

2017-05-04 20:24 525 查看
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)

思路:此题类似于3Sum这道题,在3Sum那道题的基础上稍微修改一下即可http://blog.csdn.net/yf_li123/article/details/71176581

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