Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
解题思路:(和two sum的)
- 暴力枚举
- hash
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
map<int,int> mapping;
set<vector<int>> setting;
vector<vector<int>> result;
for(int i = 0;i < nums.size();i++)
mapping[nums[i]] = i;
for(int i = 0;i < nums.size();i++) {
for (int j = i + 1; j < nums.size(); j++) {
int gap = 0 - nums[i] - nums[j];
if (mapping.find(gap) != mapping.end() && mapping[gap] > j) {
vector<int> res = {nums[i], nums[j], gap};
sort(res.begin(),res.end());
setting.insert(res);
}
}
}
for(auto a : setting){
result.push_back(a);
}
return result;
}
};