LeetCode15 3sum

Given an array S of n integers, are there elements a , b , c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

这个题的主要难度在于消除重复,我们其实很容易找到所有加起来等于0的三个数的集合,但是要控制不重复还是很难的。下面的做法使用的是map来保存已经出现过的加数,遇到第一个加数的时候,首先检查map1里有没有保存着这个加数,如果有,表示以这个数作为第一个加数的所有情况已经被找过了,直接跳过就好了。查看第二个和第三个加数是否满足条件时也是一样,在第一个加数已经确定的情况下,如果这两个加数都已经在map2种出现过,说明这种情况已经被记录过了,应该跳过。当第一个加数作为第一个加数的左右情况都被检查过之后,应当清空map2来给下一个可能的组合使用。

vector<vector<int>> threeSum(vector<int>& nums) {
        int n=nums.size();
        vector<vector<int>> anss;
        sort(nums.begin(),nums.end());
        unordered_map<int,int> check1;
        unordered_map<int,int> check2;
        for(int i=0;i<n;i++){
            if(check1.find(nums[i])!=check1.end())continue;
            check1[nums[i]]=i;
            int target=-nums[i];
            int l=i+1;
            int h=n-1;
            check2.clear();
            while(l<h){
                if(check2.find(nums[l])!=check2.end()&&check2.find(nums[h])!=check2.end()){
                    l++;h--;
                    continue;
                }
                int temp=nums[l]+nums[h];
                if(temp==target){
                    vector<int> tmp;
                    tmp.push_back(nums[i]);
                    tmp.push_back(nums[l]);
                    tmp.push_back(nums[h]);
                    anss.push_back(tmp);
                    check2[nums[l]]=l;
                    check2[nums[h]]=h;
                    l++;h--;
                }
                if(temp>target)h--;
                if(temp<target)l++;
            }
        }        
        return anss;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值