暴力去重
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { map<int, int> cnt; int n = nums.size(); for(int i = 0; i < n; i++) { if(cnt[nums[i]] == 0) cnt[nums[i]] = 1; else cnt[nums[i]]++; } vector<vector<int> > ret; sort(nums.begin(), nums.end()); for(int i = 0; i < n; i++) { if(i > 0 && nums[i] == nums[i - 1]) continue; for(int j = i + 1; j < n; j++) { // cout << nums[j] << " " << nums[j - 1] << endl; if((j > i + 1) && (nums[j] == nums[j - 1])) { continue; } vector<int> temp; int kk = 0 - (nums[i] + nums[j]); if(kk < nums[j]) continue; if((kk == nums[j] && cnt[kk] > 1) || kk != nums[j] && cnt[kk]) { if(kk == nums[i]) { if(i > 1 && kk == nums[i - 1]) continue; if(cnt[kk] >= 3) { temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(kk); } } else{ temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(kk); } // cout << nums[i] << " " << nums[j] << " " << kk << " " << r << endl; } if(temp.size() == 3) { sort(temp.begin(), temp.end()); ret.push_back(temp); } } } // sort(ret.begin(), ret.end()); // int k = unique(ret.begin(), ret.end()) - ret.begin(); // cout << k << " " << ret.size() << endl; vector<vector<int> > R; for(int i = 0; i < ret.size(); i++) { R.push_back(ret[i]); } return R; } };
second solusion:
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { map<int, int> vis; vector<int> N; int cnt = 1; int n = nums.size(); sort(nums.begin(), nums.end()); for(int i = 0; i < n; i++) { vis[nums[i]] = 1; if(i == 0) cnt = 1; else { if(nums[i] == nums[i - 1]) cnt++; else cnt = 1; } if(cnt < 3 && nums[i] != 0) N.push_back(nums[i]); else if(nums[i] == 0 && cnt <= 3) N.push_back(nums[i]); } vector<vector<int> > ret; n = N.size(); for(int i = 0; i < n && N[i] <= 0; i++) { if(i > 0 && N[i] == N[i - 1]) continue; for(int j = i + 1; j < n; j++) { if(j > i + 1 && N[j] == N[j - 1]) continue; vector<int> temp; int k = 0 - (N[i] + N[j]); if(k < N[j]) continue; if(k == N[j]) { if(j + 1 < n && N[j + 1] == k) { temp.push_back(N[i]); temp.push_back(N[j]); temp.push_back(N[j]); } } else if(N[i] == 0 && k == 0) { temp.push_back(0); temp.push_back(0); temp.push_back(0); } else if(N[i] != 0 && vis[k]) { temp.push_back(N[i]); temp.push_back(N[j]); temp.push_back(k); } if(temp.size() == 3) ret.push_back(temp); } } return ret; } };