leetcode—3sum

1.题目描述

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.
 
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)

2.解法分析

之前做过3sum closest的题目,很显然,那里的思路应用到这里是绝对可行的, 但是这个题目我觉得可以用hashmap来做,结果就写了个基于hash的程序,可是结果总是差点,检查了好半天没检查出来,先记录一下

class Solution {
public:
 
    vector<vector<int> > threeSum(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > result;
        int numSize=num.size();
        if(numSize<2)return result;
        
        sort(num.begin(),num.end());
        unordered_multiset<int> myHash;
        
        for(int i =0;i<num.size();++i)
        {
            myHash.insert(num[i]);
        }
        
        int thirdNum=0;
        vector<int>cur;
        cur.assign(3,1);
        
        for(int i=0;i<num.size()-2;++i)
        {
            if(i>0&&num[i-1]==num[i])break;
            if(num[i]>0)break;
            
            if(num[i]!=num[i+1]&&myHash.count(num[i])>0)myHash.erase(num[i]);
            for(int j=i+1;j<num.size()-1;++j)
            {
                thirdNum=0-num[i]-num[j];
                if(thirdNum<num[j])break; 
                if(num[j+1]!=num[j])myHash.erase(num[j]);
                if(myHash.count(thirdNum)>0)
                {
                    if(cur[0]!=num[i]||cur[1]!=num[j]||cur[2]!=thirdNum)
                    {
                        cur[0]=num[i];cur[1]=num[j];cur[2]=thirdNum;
                        result.push_back(cur);
                    }      
                }
              
            }
        }
        
        
        return result;
    }
    
 
};
posted @ 2013-08-22 22:04  曾见绝美的阳光  阅读(249)  评论(0编辑  收藏  举报