15. 3Sum
Difficulty: Medium
Topics: Array, Two Pointers
Similar Questions:
Problem:
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] ]
Solutions:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
if (i > 0 && nums[i] == nums[i-1]) continue; // deduplication
int sum = -nums[i];
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
if (nums[left] + nums[right] == sum) {
if (result.size() == 0 || result.back()[1] != nums[left] || result.back()[2] != nums[right]) // deduplication
result.push_back({nums[i], nums[left], nums[right]});
left++;
right--;
} else if (nums[left] + nums[right] > sum) {
right--;
} else {
left++;
}
}
}
return result;
}
};