15.3Sums
Opened this issue · 0 comments
niuworld commented
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:
- 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)
Solution:
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > retVec;
if (num.size()<3) return retVec;
std::sort(num.begin(), num.end());
for(int i=0; i<num.size()-2;i++) {
if(num[i]>0) break;
for(int j=i+1; j<num.size()-1;j++) {
if(num[i] + num[j] >0) break;
for(int k=j+1; k<num.size(); k++) {
if(num[i] + num[j] + num[k] == 0) {
vector<int> newVec;
newVec.push_back(num[i]);
newVec.push_back(num[j]);
newVec.push_back(num[k]);
std::sort(newVec.begin(), newVec.end());
retVec.push_back(newVec);
} else if (num[i] + num[j] + num[k] > 0)
break;
while (k<num.size()-1 && num[k+1] == num[k]) k++;
}
while (j<num.size()-2 && num[j+1] == num[j]) j++;
}
while (i<num.size()-3 && num[i+1] == num[i]) i++;
}
return retVec;
}
};