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)Analysis:
Solutions:
C++:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > results;
if(num.size() < 3)
return results;
sort(num.begin(), num.end());
int size = num.size();
for(int i = 0; i < size - 2; ++i) {
if(i > 0 && num[i] == num[i - 1])
continue;
int target = 0 - num[i];
for(int start = i + 1, end = size - 1; start < end;) {
if(target == num[start] + num[end]) {
vector<int> result;
result.push_back(num[i]);
result.push_back(num[start]);
result.push_back(num[end]);
results.push_back(result);
for(start += 1; start < end && num[start] == num[start - 1]; ++start) {}
for(end -= 1; start < end && num[end] == num[end + 1]; --end) {}
} else if(target < num[start] + num[end]) {
for(end -= 1; start < end && num[end] == num[end + 1]; --end) {}
} else {
for(start += 1; start < end && num[start] == num[start - 1]; ++start) {}
}
}
}
return results;
}
Java
:
Python: