您的位置:首页 > 其它

【Leetcode】【Medium】3Sum Closest

2015-01-26 22:09 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).

解题:数字求和问题,除了使用hash表使查找复杂度降为o(1)外,没有其他特别的方法。基本的思路都是枚举某一个数,然后计算余下的数字组合;本题先对数组进行排序,然后以某一个数为基准,设置两个指针从两头操作余下的数,计算三数的和,如果和大于target,右指针左移,反之,左指针右移。期间不断记录离target最近的sum值。总时间复杂度o(nlogn) + o(n2) = o(n2)需要用到C++ abs函数,求绝对值。代码:(由于题目中说一定存在一个答案,因此省略判断某些边界情况)
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
sort(num.begin(), num.end());
int size = num.size();
int min_gap = INT_MAX;

for (int i = 0; i < size; ++i) {
int j = i + 1;
int k = size - 1;

while (j < k) {
int cur_gap = num[i] + num[j] + num[k] - target;
if (abs(cur_gap) < abs(min_gap))
min_gap = cur_gap;

if (cur_gap > 0)
--k;
else if (cur_gap < 0)
++j;
else
return target;
}
}

return target + min_gap;
}
};

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: