9 3Sum
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] ]
一开始想用暴力法先提交个答案,没想到超时了。后来参照twoSum又写了一版,用map查找第三个数,没想到又超时了。。。贴一下我的超时代码:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
if(nums.size()<3) return ans;
map<int,int> mydict;
for(int i=0;i<nums.size();i++)
{
mydict[nums[i]] = i;
}
//brute force
for(int i=0;i<nums.size();i++)
{
for(int j=i+1;j<nums.size();j++)
{
int res = 0 - nums[i] - nums[j];
auto it = mydict.find(res);
if((it != mydict.end()) && (it->second > j))
{
vector<int> temp;
temp.push_back(nums[i]);
temp.push_back(nums[j]);
temp.push_back(res);
std::sort(temp.begin(),temp.end());
ans.push_back(temp);
}
}
}
//delete duplicates
std::sort(ans.begin(),ans.end());
ans.erase(unique(ans.begin(),ans.end()), ans.end());
return ans;
}
};
后来想了很久也没什么特别的思路,决定去讨论区参照一下已有的算法,附上参考的算法链接:https://leetcode.com/problems/3sum/discuss/274024/C%2B%2B-93.31100ms100(14.5M)-.
这个算法的新奇之处在于在将原有数组进行了从小到大的排序,这样通过从排序后的数组两头逼近来求取和为零的组合,真是神操作(速度超越95%)。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
if(nums.size()<3) return ans;
//sort
std::sort(nums.begin(),nums.end());
int len = nums.size();
//
for(int i=0;i<len-2;i++)
{
if(i>0 && nums[i] == nums[i-1]) continue;
if(nums[i] + nums[i+1] + nums[i+2] > 0) break;
if(nums[i] + nums[len-2] + nums[len-1] <0) continue;
int j=i+1, k = len -1;
while(j<k)
{
int sum = nums[i] + nums[j] + nums[k];
if(sum > 0) k--;
else if(sum<0) j++;
else{
ans.push_back({nums[i],nums[j],nums[k]});
do{j++;}while(nums[j] == nums[j-1] && j<k );
do{k--;}while(nums[k] == nums[k+1] && j<k );
}
}
}
return ans;
}
};