• [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;
        }
    };
  • 相关阅读:
    函数-列表生成式
    函数-闭包
    函数-参数
    函数-装饰器
    函数-函数递归
    函数-高阶函数
    函数-命名空间
    函数-匿名函数
    模块-shutil
    在 Android 5.1.1 执行 remount system failed 解决方法
  • 原文地址:https://www.cnblogs.com/grandyang/p/5940677.html
Copyright © 2020-2023  润新知