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
sort(num.begin(), num.end());
vector<vector<int> > ans;
vector<int> temp;
for (int i = 0; i < num.size(); i++) {
if (i > 0 && num[i] == num[i - 1]) {
continue;
}
for (int j = i + 1; j < num.size(); j++) {
if (num[j] == num[j - 1] && j - 1 > i) {
continue;
}
int k = - num[i] - num[j];
int left = j + 1, right = num.size() - 1, mid = 0;
while (left <= right) {
mid = (left + right) >> 1;
if (num[mid] > k) {
right = mid - 1;
}
else if (num[mid] == k) {
temp.push_back(num[i]);
temp.push_back(num[j]);
temp.push_back(num[mid]);
ans.push_back(temp);
temp.clear();
break;
}
else {
left = mid + 1;
}
}
}
}
return ans;
}
};