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.

这个题跟我storm8的电面题差不多,可惜当时脑子没转过来,是在人家给了hint之后做出来的。就挂了。


class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        unordered_set<int> map;
        int n = num.size();
        for(int i = 0;i < n; ++i){
            map.insert(num[i]);
        }
        int max = 1;
        for(int i = 0; i< n; ++i){
            if(map.find(num[i]) != map.end()){
                int temp = 1;
                int cur = num[i];
                map.erase(cur);
                temp += getCount(map, cur + 1, true);
                temp += getCount(map, cur - 1, false);
                max = temp > max ? temp : max;
            }
        }
        return max;
    }
    int getCount(unordered_set<int> &map, int cur, bool asc){
        int count = 0;
        while(map.find(cur) != map.end()){
            map.erase(cur);
            count ++;
            if(asc)
                cur++;
            else
                cur--;
        }
        return count;
    }
};


你可能感兴趣的:(Longest Consecutive Sequence)