class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
typedef vector<int>::size_type sz;
typedef map<int, sz>::const_iterator iter;
vector<vector<int> > ret;
map<int, sz> nMap;
for (sz i = 0; i < nums.size(); ++i) {
++ nMap[nums[i]];
cout << nMap[nums[i]];
}
for (iter it1 = nMap.begin(); it1 != nMap.end(); ++it1) {
if (it1->first == 0 && it1->second >= 3) {
vector<int> tmp(3, 0);
ret.push_back(tmp);
}
int num1 = it1->first;
iter it2 = it1;
for ( ++it2; it2 != nMap.end(); ++it2) {
int num2 = it2->first;
int num3 = 0 - num1 - num2;
iter it3 = nMap.find(num3);
if (it3 == nMap.end()) continue;
if (((num3 == num1 || num3 == num2) && it3->second >= 2)
|| num3 > num2){
vector<int> tmp;
tmp.push_back(num1);
tmp.push_back(num2);
tmp.push_back(num3);
ret.push_back(tmp);
}
}
}
return ret;
}
};
参考后
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
if (nums.size() < 3) return vector<vector<int> >();
typedef vector<int>::size_type sz;
sort(nums.begin(), nums.end());
vector<vector<int> > ret;
for (sz i = 0; i != nums.size() - 2; ++i) {
int twoSum = 0 - nums[i];
sz j = i + 1;
sz k = nums.size() - 1;
while (j < k) {
if (nums[j] + nums[k] == twoSum) {
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[k]);
ret.push_back(tmp);
while (j < k && nums[j] == nums[j + 1]) ++j;
while (j < k && nums[k] == nums[k - 1]) --k;
++j;
--k;
} else if (nums[j] + nums[k] < twoSum) {
while (j < k && nums[j] == nums[j + 1]) ++j;
++j;
} else {
while (j < k && nums[k] == nums[k - 1]) --k;
--k;
}
}
while (i + 1 < nums.size() - 2 && nums[i] == nums[i + 1]) ++i;
}
return ret;
}
};