Given an array nums of n integers, are there elements a, b, c in nums 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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[ [-1, 0, 1], [-1, -1, 2] ]
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
int n = nums.size();
for(int i =0;i<n;i++){
if(i== 0 || (i!=0 && nums.at(i) != nums.at(i-1)) ){
int a = nums.at(i);
int l = i+1;
int r = n-1;
int target = -a;
while(l<r){
int sum = nums.at(l) + nums.at(r);
if(sum == target){
result.push_back({a,nums.at(l),nums.at(r)});
while(l < r && nums.at(l) == nums.at(l+1))
l++;
while(l < r && nums.at(r) == nums.at(r-1))
r--;
l++;r--;
}else if(sum > target){
r--;
}else{
l++;
}
}
}
}
return result;
}
};









网友评论