3Sum

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的升级版。依然用了map。用的时候注意当前使用元素应该删除。
class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        map<int , int>m;
        vector< vector<int> >re;
        for(int i = 0 ; i < num.size();i++)
        m[num[i]]++;
        
        for(map<int,int>::iterator it = m.begin() ; it != m.end();it++)
        {
            int now = it->first;
            int target = 0 - now;
            m[now]--;
            for(map<int,int>::iterator iter = it ; iter!= m.end() ; iter++)
            {
                if(iter->second <= 0)continue;
                m[iter->first]--;
                int tar = target - iter->first;
                if(m.find(tar) != m.end()&&tar>=iter->first&&m[tar]>0)
                {
                    vector<int> tmp;
                    tmp.push_back(it->first);
                    tmp.push_back(iter->first);
                    tmp.push_back(tar);
                    re.push_back(tmp);
                }
                m[iter->first]++;
            }
            m[now]++;
        }
        return re;
    }
};

  该代码没有考虑去重的问题,但是在实际中去重是应该考虑的。由于结果vector是排序好的,即此处的vector可以当set用,(1,0,1)、(0,1,1)只会以(0,1,1)的形式出现。因此可以为结果vector建立一个hash表,在结果vector插入之前,查看当前结果是否已经在hash中出现,如果出现过就不放进结果里。

posted on 2014-03-06 21:27  pengyu2003  阅读(188)  评论(0编辑  收藏  举报

导航