leetcode Longest Consecutive Sequence

题目连接

https://leetcode.com/problems/longest-consecutive-sequence/  

Longest Consecutive Sequence

Description

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 {
private:
    typedef vector<int> vec;
    typedef unordered_map<int, bool> UMAP;
public:
    int longestConsecutive(vec &nums) {
        if(nums.empty()) return 0;
        UMAP vis;
        int ans = 0;
        for(auto &r: nums) vis[r] = false;
        for(auto &r: nums) {
            if(vis[r]) continue;
            int ret = 1;
            vis[r] = true;
            for(int j = r + 1; vis.find(j) != vis.end(); j++) {
                vis[j] = true;
                ret++;
            }
            for(int j = r - 1; vis.find(j) != vis.end(); j--) {
                vis[j] = true;
                ret++;
            }
            ans = max(ans, ret);
        }
        return ans;
    }
};
posted @ 2015-12-09 20:15  GadyPu  阅读(161)  评论(0编辑  收藏  举报