0% found this document useful (0 votes)
18 views1 page

3sum

The provided code defines a C++ class Solution with a method threeSum that finds all unique triplets in an array that sum to zero. It sorts the input array and uses a two-pointer technique to efficiently find the triplets. The method returns a vector of vectors containing the triplets that meet the criteria.

Uploaded by

Ayush Saklani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views1 page

3sum

The provided code defines a C++ class Solution with a method threeSum that finds all unique triplets in an array that sum to zero. It sorts the input array and uses a two-pointer technique to efficiently find the triplets. The method returns a vector of vectors containing the triplets that meet the criteria.

Uploaded by

Ayush Saklani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solution {

public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin() , nums.end());
if(nums.size() < 3) return {};
if(nums[0] > 0) return {};
vector<vector<int>> res;
for(int i = 0 ; i < nums.size() ; i++){
if(nums[i] > 0) break;
if(i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1 , r = nums.size() - 1;
int sum = 0;
while(l < r){
sum = nums[i] + nums[l] + nums[r];
if(sum > 0) r--;
else if(sum < 0) l++;
else{
res.push_back({nums[i] , nums[l] , nums[r]});
int l_last = nums[l] , r_last = nums[r];
while(l < r && nums[l] == l_last) l++;
while(l < r && nums[r] == r_last) r--;
}
}
}
return res;
}
};

You might also like