3Sum —— Leetcode

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
首先,这题与2sum有着异曲同工之妙,只是难点在于排除重复的三元组。

以下是我的思路:

以{-1, -1, 0, 0, 0, 1, 2, 4}为例:首先,将所有数hash到一个hashmap中,unordered_map<int, int>,key为数,value为出现的次数。

假设hashtable的内容如下:

     [-1    0   1    2  4] 数字      

     [2     3    1  1  1] 出现次数     

两个指针i, j,j从0到最后,每次移动一个位置;i每一个循环中从0移到j;

每次循环中,i和j各用掉一个“出现次数”,那么就要判断0-num[i]-num[j]在hashtable中是否有出现次数,并且该数要大于num[j](由大到小找,防止重复)。

最后得出的结果就是不重复的所有sum三元组,这样,排序时间复杂度为O(nlgn),处理的时间复杂度为O(n^2)。

以下是源码(在leetcode上跑的结果是 超时,但我认为这个方法不错,就记录了下来)

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        //排序
        vector<vector<int>> res;
        std::sort(num.begin(), num.end());
        
        //hashtable统计
        unordered_map<int, int> ht;
        for(int k=0; k<num.size(); ++k) {
            ht[num[k]]++;
        }
        
        //将num缩为不重复vector
        vector<int>::iterator it = std::unique(num.begin(), num.end());
        num.erase(it, num.end());
        
        int p1, p2;
        for(int j=0; j<num.size(); ++j) {
        	p2 = num[j];
            for(int i=0; i<=j; ++i) {
                unordered_map<int, int> tmp_ht(ht);
                p1 = num[i];
                
                tmp_ht[p1]--;
                tmp_ht[p2]--;
                
                int targetNumber = 0 - p1 - p2;
                
                if(ht[targetNumber]!=0 && p2<=targetNumber) {
                    res.push_back({p1, p2, targetNumber});
                }
            }
        }
        
        return res;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值