0
点赞
收藏
分享

微信扫一扫

lintcode:3 Sum

敬亭阁主 2022-12-01 阅读 66


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.

Example
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is:

(-1, 0, 1)
(-1, -1, 2)
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.

class Solution {
public:
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int> > threeSum(vector<int> &nums) {
// write your code here
sort(nums.begin(),nums.end());

vector<vector<int> > res;

for(int i=0;i<nums.size();i++){

if(i>=1&&nums[i]==nums[i-1]){
continue;
}

int pa=i+1;
int pb=nums.size()-1;

bool first=true;

int sum=0;

while(pa<pb){


sum=nums[i]+nums[pa]+nums[pb];

if(sum==0){

if(!first&&nums[pa]==nums[pa-1]){
pa++;
continue;
}
if(!first&&nums[pb]==nums[pb+1]){
pb--;
continue;
}

vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[pa]);
tmp.push_back(nums[pb]);

res.push_back(tmp);

pa++;
pb--;

if(first){
first=false;
}


}else if(sum<0){
pa++;
}else{
pb--;
}



}

}
return res;
}
};

跟3sum closest类似
注意排除重复triplets的方式


举报

相关推荐

0 条评论