## 3Sum

06/25/2016 Array Two Pointers

## Question

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]
]


## Solution

Result: Accepted Time: 56ms

Here should be some explanations.

class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ret;
const int n = nums.size();

sort(nums.begin(), nums.end());
for (int i = 0; i < n-2; ++i)
{
if (nums[i] > 0)
break;
if (i != 0 && nums[i] == nums[i-1])
continue;

int target = 0 - nums[i];
int left = i + 1;
int right = n - 1;

while (left < right)
{
if (nums[right] < 0)
break;
if ((nums[left] + nums[right]) == target)
ret.push_back(vector<int>{nums[i],nums[left],nums[right]});

if ((nums[left] + nums[right]) < target)
{
++left;
while (left < right && nums[left-1] == nums[left]) ++left;

}
else
{
--right;
while (left < right && nums[right+1] == nums[right]) --right;
}
}
}
return ret;
}
};


Complexity Analytics

• Time Complexity: $O(n^2)$
• Space Complexity: $O(1)$