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] ]
三个数字和为0,要求不重复。
首先想到用2Sum的方法,先确定一个数,然后内部循环使用2Sum的哈希算法。最后对结果去重。
结果超时了。贴上代码
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; if (nums.empty()) return res; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); ++i) { int target = 0-nums[i]; unordered_set<int> set; vector<int> tmp; tmp.push_back(nums[i]); for (int j = i+1; j < nums.size(); ++j) { if (set.count(target-nums[j]) > 0) { tmp.push_back(target-nums[j]); tmp.push_back(nums[j]); } if (tmp.size() == 3) { res.push_back(tmp); tmp.clear(); tmp.push_back(nums[i]); //set.clear(); } set.insert(nums[j]); } } for (auto i = res.begin(); i != res.end(); ++i) { vector<int> vec1 = *i; sort(vec1.begin(), vec1.end()); for (auto j = i+1; j != res.end(); ++j) { vector<int> vec2 = *j; sort(vec2.begin(), vec2.end()); if (vec1 == vec2) { j = res.erase(j); j--; } } } return res; } };
看了看大佬们的答案,豁然开朗
将数组排序,然后确定一个数,再使用二分查找的方法。
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; if (nums.empty()) return res; sort(nums.begin(), nums.end()); for (int k = 0; k < nums.size(); ++k) { if (nums[k] > 0) break; if (k > 0 && nums[k] == nums[k-1]) continue; int target = 0 - nums[k]; int i = k + 1, j = nums.size() - 1; while (i < j) { if (nums[i] + nums[j] == target) { res.push_back({nums[k], nums[i], nums[j]}); while (i < j && nums[i] == nums[i+1]) ++i; while (i < j && nums[j-1] == nums[j]) --j; ++i; --j; } else if (nums[i] + nums[j] < target) ++i; else --j; } } return res; } };