Saturday, March 23, 2013

Longest Consecutive Sequence

/*
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(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = num.size();
        if(size==0) return 0;
        if(size==1) return 1;
        int const MaxNum = 50000;
        int const offset = MaxNum/2;
        vector<bool> existNum;
        existNum.insert(existNum.begin(), MaxNum, false);
        int i;
        for(i=0; i<size; i++){
          if((num[i]+offset) > MaxNum || (num[i]+offset) <0 ) return 0;
          existNum[num[i]+offset] = true;
        }
        int longest = 0;
        int currSum = 0;
        for(i=0; i<MaxNum; i++){
           if(i==0 && existNum[i]==true){
             currSum = 1;
           }
           if(i>0 && existNum[i-1]==true && existNum[i]==1){
            currSum++;
           }
           if(i>0 && existNum[i-1]==0 && existNum[i]==1){
            currSum = 1;
           }
           if(i>0 && existNum[i-1]==1 && existNum[i]==0){
            longest = max(longest, currSum);
            currSum = 0;
           }
          
           if(i==MaxNum-1){
            longest = max(longest, currSum);
           }
        }
       
        return longest;
    }
};

No comments:

Post a Comment