难度:medium
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: 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] ]
思路:可以用3重循环来暴力破解,但是这样的话复杂度是O(n^3)
我们可以先排序数据,然后定住一个数,剩下的数做2Sum中的两端逼近的算法,这样算法的复杂度就变成了O(n^2)
代码:
#include <algorithm>
#include <set>
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& num) {
vector<int> nums = num;
vector<vector<int>> result;
set<vector<int>> s;
sort(nums.begin(),nums.end());
for (int i = 0; i < nums.size(); i++){
int value = nums[i];
int begin = i+1;
int end = nums.size()-1;
while (begin < end){
if (nums[begin]+nums[end] == -value){
vector<int> temp({value,nums[begin],nums[end]});
if (s.find(temp) == s.end()){
result.push_back(temp);
s.insert(temp);
}
end--;
begin++;
} else if (nums[begin]+nums[end] > -value){
end--;
} else {
begin++;
}
}
}
return result;
}
};
set是用来去重的