您的位置:首页 > 其它

3Sum Closest题解

2016-01-31 22:00 309 查看
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).


翻译:

给定一个数列个一个目标target,找到三个数字,使得这三个数字之和与target最接近,返回三个数的和,假定只有唯一解

分析:

这题乍看有点蹊跷,仔细分析实际跟3sums是一样的,只不过3sums是与terget“相等”,这题是“最接近”,我们只要追加一个变量temp,初始temp取无穷大,然后每次存储abs(sum-target),最终返回最小的temp对应的sum就可以了

这里我们介绍一种新的方法,就是我们上篇文章中提及的不用辅助空间的方法

假设我们有三个指针i,j,k:

首先我们对array排序,sum=s[i]+s[j]+s[k]

i指向一个位置,i将array分成了两部分,0~i和i+1~n-1,0~i这部分是已经处理过的部分,i+1~n-1是待处理的部分

我们将j指向i+1 ;k指向n-1,然后像一次快排一样

如果sum < target,说明sum太小,此时j++让sum变大,

如果sum > target,说明sum太大,此时k–让sum变小,

如果sum==target,说明已经找到元素,返回就可以

由于每次移动指针会根据temp判断是否保存sum,最后sum保存的一定是最接近target的值:

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result = 0;
int temp = 99999;
if (nums.size() <= 2) return NULL;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
int j = i + 1;
int k = nums.size() - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum - target == 0)
return sum;
if (sum - target < 0) {
if (abs(sum - target) <= temp) {
result = sum;
temp = abs(sum - target);
}
j++;
}
if (sum - target > 0) {
if (abs(sum - target) <= temp) {
result = sum;
temp = abs(sum - target);
}
k--;
}
}
}
return result;
}
};


STL中的sort()使用快排,时间复杂度为O(nlogn),又只增加了常数个变量,所以最终时间复杂度为O(n²),空间为O(1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: