题目:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)分析与解答:
从简单的情况开始考虑,比如只需要计算两个数的和是不是等于0,复杂度O(n),方法参见two sum。所以对于3sum一开始我也尝试寻找线性时间内的解,后来发现难度较大。退而求其次,因为结果要求是有序的,那就先排序吧,但即便是有序之后依然需要O(n^2)的时间。所以此题并未找到更简单的解法,在wiki上的方法是和我一样的。三个指针,固定一个,然后另两个一头一尾进行遍历。
需要注意的是:题目要求不能有重复结果。所以要想办法剔除相同的数字。三个指针分别指向三个数,当每个指针在自己的合法范围内碰到相同的数字,就直接跳过即可。
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
if (num.empty() || num.size() < 3)
return result;
sort(num.begin(), num.end()); //排个序先
int head = 0, end = 0;
for (int i = 0; i < num.size() - 2; i++) {
while (i && (num[i] == num[i - 1])) {
i++;
}
head = i + 1, end = num.size() - 1;
while (head < end) {
if (num[i] + num[head] + num[end] == 0) {
int t[3] = { num[i], num[head], num[end] };
vector<int> temp(t, t + 3);
result.push_back(temp);
while (head < end && (temp[1] == num[head]))
head++;
while (head < end && (temp[2] == num[end]))
end--;
} else if (num[i] + num[head] + num[end] > 0)
end--;
else
head++;
}
}
return result;
}
};