24. 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.

两种方法:1. 利用 hash_map 结构,数组有序时查找的思想。

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        if(num.size() == 0) return 0;
        unordered_map<int, bool> _map;
        for(size_t i = 0; i < num.size(); ++i)  
            _map.insert(pair<int ,bool>(num[i], false));
        int ans = 0;
        for(auto it = _map.begin(); it != _map.end(); ++it) {
            if(it->second) continue; // visited
            int len = 1;
            int v1 = it->first-1;
            while(_map.count(v1))  { _map[v1--] = true; len++; }
            int v2 = it->first+1;
            while(_map.count(v2)) { _map[v2++] = true; len++; }
            if(len > ans) ans = len;
        }
        return ans;
    }
};

 2. 动态的构造线段(两端为线段始末位置),这样从一端点可获取另一端点位置。若当前点可增加有向线段长度,拓展线段。

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        int answer = 0;
        unordered_map<int ,int>_map;
        int low, high;
        for(int i = 0; i < num.size(); ++i) {
            if(_map.count(num[i])) continue; // must be used.
            _map[num[i]] = num[i];
            low = high = num[i];
            if(_map.count(num[i]-1)) low = _map[num[i]-1];
            if(_map.count(num[i]+1)) high = _map[num[i]+1];
            answer = max(answer, high - low + 1);
            if(low == high) continue;// not in a line
            _map[low] = high;
            _map[high] = low;
        }
        return answer;
    }
};
原文地址:https://www.cnblogs.com/liyangguang1988/p/3938543.html