zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    常见SQL语句
    测试用例的设计
    移动端测试注意事项
    markdown编辑模式基本使用
    常用修改请求或返回方法
    前端性能测试工具Lighthouse
    presto环境部署
    pyenv管理python版本
    python2.6.6升级python2.7.14
    InfluxDB权限认证机制
  • 原文地址:https://www.cnblogs.com/grandyang/p/5940677.html
Copyright © 2011-2022 走看看