思路
找出三个数之和,三层for循环肯定会超时,所以可以将每个数的频次记录在map中(pair为(数,频次)),这样map就记录了所有的数以及他们出现的频次。
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
map<int, int> counter;
for (int i = 0; i < nums.size(); i++)
counter[nums[i]] ++;
vector<vector<int>> res;
auto iter1 = counter.begin();
for (; iter1 != counter.end(); iter1++) {
auto tepIter = iter1;
for (auto iter2 = ++tepIter; iter2 != counter.end(); iter2++) {
if (iter1->first * 2 + iter2->first == 0 && iter1->second >= 2&& iter2->second >= 1) {
res.push_back({ iter1->first, iter1->first, iter2->first });
}
if (iter1->first + iter2->first * 2 == 0 && iter2->second >= 2 && iter1->second >= 1) {
res.push_back({ iter1->first, iter2->first, iter2->first });
}
int c = 0 - iter1->first - iter2->first;
if (c > iter2->first && counter[c] != 0) {
res.push_back({ iter1->first, iter2->first, c });
}
}
}
if (counter[0] >= 3)
res.push_back({ 0, 0, 0 });
return res;
}
};
int main() {
vector<int> nums1 = { -1,-2,-3,4,1,3,0,3,-2,1,-2,2,-1,1,-5,4,-3 };
vector<vector<int>> res = Solution().threeSum(nums1);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
system("pause");
return 0;
}