leetcode 105: Longest Consecutive Sequence

Longest Consecutive SequenceFeb 14

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
        unordered_map<int,int> mymap;
        unordered_set<int> unique; 
        int max = 0;
        
        for(int i=0; i<num.size(); i++) {
            if(unique.find(num[i])!=unique.end()) {
                continue;
            } else {
                unique.insert(num[i]);
            }
            
            int left=num[i], right = num[i];
            
            if(mymap.find(left-1)!=mymap.end() && mymap[left-1] <= left-1) {  //should be left-1
                left = mymap[left-1];
            }
            
            if(mymap.find(right+1)!=mymap.end() && mymap[right+1] >= right+1) {  //should be right+1
                right  = mymap[right+1];
            }
            mymap[left] = right;  //don't forget put these into the map.
            mymap[right] = left;
            
            max = max > (right-left+1) ? max : (right-left+1);   //do not need to iterate map again. use var to record max value.
        }
        return max;
    }
};


posted @ 2013-03-08 04:38  西施豆腐渣  阅读(138)  评论(0编辑  收藏  举报