题目大意:给定一个数组,在里面找出3个数,这3个数的和为0
解题思路:先排序,去最前面的一个数,用双向遍历来求出两个数的和等于这个选出数的反数
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<vector<int> > result;
if(num.size() < 3) {
return result;
}
sort(num.begin(), num.end());
int pre = -1;
bool start = false;
for(int k = 0; k < num.size(); k++) {
int total = num[k];
if(start) {
if(total == pre) {
continue;
}
}
pre = total;
start = true;
int low = k + 1, high = num.size() - 1;
while(low < high) {
if(num[low] + num[high] == -total) {
vector<int> tmp;
tmp.push_back(total);
tmp.push_back(num[low]);
tmp.push_back(num[high]);
result.push_back(tmp);
low++;
high--;
while(low < high && num[low] == num[low - 1]) {
low++;
}
while(low < high && num[high] == num[high + 1]) {
high++;
}
} else if(num[low] + num[high] < -total) {
low++;
} else {
high--;
}
}
}
return result;
}
};