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]
]
方法: 排序+三个标记,算法复杂度(O2)。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
if(nums.size() < 3)
return res;
for(int first = 0; first < nums.size() -2; ++first){
if(first != 0 && nums[first] == nums[first-1])
continue;
int second = first + 1, third = nums.size() - 1;
while(second < third){
while(second != first + 1 && nums[second] == nums[second - 1]&&second < third)
++second;
if(second >= third)
break;
while(third != nums.size() - 1 && nums[third] == nums[third+1]&&second < third)
--third;
if(second >= third)
break;
int temp_sum = nums[first] + nums[second] + nums[third];
if(temp_sum > 0)
--third;
else if(temp_sum < 0)
++second;
else{
res.push_back(vector<int>{nums[first],nums[second],nums[third]});
++second;
--third;
}
}
}
return res;
}
};