题目:
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)思想:首先将数组进行排序,复杂度O(nlgn);然后固定一个数,问题就退化成2sum,复杂度O(n^2)。
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
int len = num.size();
vector<vector<int>> res;
//O(nlgn)
sort(num.begin(), num.end());
vector<int> tmp(3, INT_MIN);
//O(n^2)
for(int i = 0; i < len-2; i++) {
//之前计算过的无需再计算
if(num[i] == tmp[0])
continue;
tmp[0] = num[i];
int begin = i+1, end = len-1, target = 0 - num[i];
while(begin < end) {
int sum = num[begin] + num[end];
if(sum == target) {
tmp[1] = num[begin];
tmp[2] = num[end];
res.push_back(tmp);
begin++;
end--;
continue;
}
else if(target > sum)
begin++;
else
end--;
}
}
//使用set的目的是去重
set<vector<int>> ans(res.begin(), res.end());
res.clear();
res.insert(res.begin(), ans.begin(), ans.end());
return res;
}
};