Monday, November 25, 2013

LeetCode Problem : Longest Consecutive Sequence

Problem 



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.

Code

struct range
{
    int start;
    int finish;
};  
    
int longestConsecutive(vector<int> &num) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    unordered_map<int,bool> rmap;
    int n = num.size();
    int max_len = 0;
    for(int i = 0;i < n;++i){
        rmap.insert(make_pair(num[i],false));
    }
    for(int i = 0;i < n;++i){
        if(rmap[num[i]])
        continue;
        int next = num[i] + 1;
        while(rmap.find(next) != rmap.end()){
            rmap[next] = true;
            ++next;
        }
        int prev = num[i] - 1;
        while(rmap.find(prev) != rmap.end()){
            rmap[prev] = true;
            --prev;
        }
        int len = next - prev - 1;
        if(max_len < len)
        max_len = len;
    }
    return max_len;
}

No comments:

Post a Comment