Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

 

不是自己想出来的,但是有所改进。

题目要求O(n)。如果所有常规办法都不奏效,O(n)就只能靠hash了,必须底层不能是红黑树的哈希。

但即便用哈希,也要小心元素的重复,所以查到一个,删除一个。

关键是底层要用unordered_map

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        unordered_set<int> l;
        if(num.size()<=1)return num.size();
        for(int i = 0 ; i < num.size(); i++)
        {
            l.insert(num[i]);
        }
        
        
        int max = 1;
        for(int i = 0 ; i < num.size();i++)
        {
            if(l.find(num[i]) == l.end())continue;
            
            int temp = num[i];
            int len =1 ;
            temp--;
            while(l.find(temp)!=l.end())
            {
                l.erase(temp);
                temp--;
                len++;
            }
            temp = num[i]+1;
            
            while(l.find(temp)!=l.end())
            {
                l.erase(temp);
                temp++;
                len++;
            }
            l.erase(num[i]);
            if(len > max)max =len;
            
        }
        return max;
    }
};

  

posted on 2014-04-15 16:01  pengyu2003  阅读(170)  评论(0编辑  收藏  举报

导航