Longest Consecutive Sequence

 

    int longestConsecutive(vector<int> &num) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(num.empty())
            return 0;
        map<int,int> m;
        int max_len = 1;
        for(int i=0;i<num.size();i++)
        {
            if(m.count(num[i])>0)
                continue;
            m[num[i]] = 1;
            if(m.count(num[i]-1)>0)
                max_len = max(max_len,merge(m,num[i]-1,num[i]));
            if(m.count(num[i]+1)>0)
                max_len = max(max_len,merge(m,num[i],num[i]+1));
        }
        return max_len;
    }
    
    int merge(map<int,int>& m,int small,int big)
    {
        int lower = small-m[small]+1;
        int upper = big+m[big]-1;
        int len = upper-lower+1;
        m[lower] = len;
        m[upper] = len;
        return len;
    }

  

posted @ 2013-10-10 14:33  summer_zhou  阅读(134)  评论(0编辑  收藏  举报