Problem
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int nSize = num.size();
vector< vector<int> > result;
if (nSize < 3) return result;
sort(num.begin(), num.end());
int val = num[0] - 1;
vector<int> mid(3);
for (int i = 0; i < nSize - 2; ++i)
{
if (val == num[i]) continue;
val = num[i];
mid[0] = val;
int sum = -val;
int l = i + 1;
int r = nSize - 1;
int tmp = 0;
while(l < r)
{
tmp = num[l] + num[r];
if (tmp == sum)
{
mid[1] = num[l];
mid[2] = num[r];
result.push_back(mid);
while(num[++l] == num[l-1] && l < r);
while(num[--r] == num[r+1] && r > l);
}
else if (tmp < sum)
++l;
else
--r;
}
}
return result;
}
};