15. 3Sum
Medium
4733562FavoriteShare
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] ]
Accepted
677,938
Submissions
2,709,173
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int> > results;
int n=nums.size();
sort(nums.begin(),nums.end());
if(n<=2) return results;
for(int i=0;i<n;i++){//固定第一个数字
int j=i+1;
int k=n-1;
if(i!=0&&nums[i]==nums[i-1]) continue;//如果第一个数字有重复就右移
while(j<k){
if(nums[i]+nums[j]+nums[k]==0){
results.push_back({nums[i],nums[j],nums[k]});
j++;k--;
while(j<k&&nums[j]==nums[j-1]) j++;//第二个数字有重复则右移
while(j<k&&nums[k]==nums[k+1]) k--;//第三个数字有重复则左移
}else if(nums[i]+nums[j]+nums[k]<0){//三数之和小于0则第二个数字右移
j++;
}else{//三数之和大于0则第三个数字左移
k--;
}
}
}
return results;
}
};