Leetcode 15. 3Sum (Medium) (cpp)
Tag: Array, Two Pointers
Difficulty: Medium
/*
15. 3Sum (Medium)
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.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-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>> res;
int _size = nums.size();
if (_size < 3) {
return res;
}
sort(nums.begin(), nums.end());
for (int i = 0; i < _size - 2; i++) {
if (i > 0 && nums[i - 1] == nums[i] || nums[i] + nums[_size - 1] + nums[_size - 2] < 0) {
continue;
}
if (nums[i] + nums[i + 1] + nums[i + 2] > 0) {
break;
}
int j = i + 1, k = _size - 1;
while (j < k) {
int _sum = nums[i] + nums[j] + nums[k];
if (_sum == 0) {
res.push_back(vector<int>{nums[i], nums[j], nums[k]});
do {
j++;
} while (nums[j] == nums[j - 1] && j < k);
do {
k--;
} while (nums[k] == nums[k + 1] && j < k);
}
else if (_sum > 0) {
k--;
}
else {
j++;
}
}
}
return res;
}
};