Tuesday, December 31, 2013

[LeetCode] 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.




 
class Solution {
    public:
    int longestConsecutive(std::vector<int> &num) {
        if(num.size()==0)
            return 0;
        std::unordered_set<int> set(num.begin(), num.end());
        int max = 1;
        for(int i=0; i<num.size(); i++)
        {
            if(set.find(num[i])==set.end())
            continue;
            set.erase(num[i]);
            int l = getLen(set, num[i], -1);
            int r = getLen(set, num[i], 1);
            if(l+r+1>max)
            max = l+r+1;
        }
        return max;
    }
    int getLen(std::unordered_set<int>& set, int n, int step)
    {
        int len = 0;
        n+=step;
        while(set.find(n)!=set.end())
        {
            set.erase(n);
            len++;
            n+=step;
        }
        return len;
    }
};

No comments:

Post a Comment