15. 3Sum
Medium
4276486FavoriteShare
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;
if(nums.size() <= 2){return Result;}
sort(nums.begin(),nums.end());
for(int k = 0;k < nums.size();k++){
if(k > 0 && nums[k] == nums[k - 1]){continue;}
if(nums[k] > 0){return Result;}
int target = 0 - nums[k];
int LeftIndex = k + 1;int RightIndex = nums.size() - 1;
while(LeftIndex < RightIndex){
if(target == nums[LeftIndex] + nums[RightIndex]){
Result.push_back({nums[k],nums[LeftIndex],nums[RightIndex]});
while(LeftIndex < RightIndex && nums[LeftIndex] == nums[LeftIndex + 1]){
LeftIndex++;
}
while(RightIndex > LeftIndex && nums[RightIndex] == nums[RightIndex - 1]){
RightIndex--;
}
LeftIndex += 1;
RightIndex -= 1;
}
else if(target < nums[LeftIndex] + nums[RightIndex]){
RightIndex--;
}
else if(target > nums[LeftIndex] + nums[RightIndex]){
LeftIndex++;
}
}
}
return Result;
}
};