[LintCode] Longest Consecutive Sequence 求最长连续序列

简介:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Clarification

Your algorithm should run in O(n) complexity.

Example

Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length: 4.

LeetCode上的原题,请参见我之前的博客Longest Consecutive Sequence

解法一:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    int longestConsecutive(vector<int> &num) {
        int res = 0;
        unordered_set<int> s(num.begin(), num.end());
        for (int d : num) {
            if (!s.count(d)) continue;
            s.erase(d);
            int pre = d - 1, next = d + 1;
            while (s.count(pre)) s.erase(pre--);
            while (s.count(next)) s.erase(next++);
            res = max(res, next - pre - 1);
        }
        return res;
    }
};

解法二:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    int longestConsecutive(vector<int> &num) {
        int res = 0;
        unordered_map<int, int> m;
        for (int d : num) {
            if (m.count(d)) continue;
            int left = m.count(d - 1) ? m[d - 1] : 0;
            int right = m.count(d + 1) ? m[d + 1] : 0;
            int sum = left + right + 1;
            m[d] = sum;
            res = max(res, sum);
            m[d - left] = sum;
            m[d + right] = sum;
        }
        return res;
    }
};

本文转自博客园Grandyang的博客,原文链接:求最长连续序列[LintCode] Longest Consecutive Sequence ,如需转载请自行联系原博主。

相关文章
UVa787 - Maximum Sub-sequence Product(最大连续乘积子串)
UVa787 - Maximum Sub-sequence Product(最大连续乘积子串)
49 0
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
|
机器学习/深度学习 缓存 算法
【欧拉计划第 14 题】 最长的考拉兹序列 Longest Collatz sequence
【欧拉计划第 14 题】 最长的考拉兹序列 Longest Collatz sequence
378 0
【欧拉计划第 14 题】 最长的考拉兹序列 Longest Collatz sequence