zoukankan      html  css  js  c++  java
  • 23longest-consecutive-sequence

    题目描述

    给定一个无序的整数类型数组,求最长的连续元素序列的长度。
    例如:
    给出的数组为[100, 4, 200, 1, 3, 2],
    最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
    你需要给出时间复杂度在O(n)之内的算法

    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

    输入

    复制
    [100, 4, 200, 1, 3, 2]

    输出

    复制
    4
    
    class Solution {
    public:
        /**
         *
         * @param num int整型vector
         * @return int整型
         */
        int longestConsecutive(vector<int>& num) {
            // write code here
            set<int> Set(num.begin(),num.end());
            int result=1;
            for (int x:num)
            {
                if (Set.find(x)==Set.end())
                    continue;
                Set.erase(x);
                int l=x-1,r=x+1;
                while (Set.find(l)!=Set.end())
                    Set.erase(l--);
                while (Set.find(r)!=Set.end())
                    Set.erase(r++);
                result=max(result,r-l-1);
                
            }
            return result;
        }
        
    };

  • 相关阅读:
    mupdf arm 交叉编译记录
    lua的closure创建和使用
    Lua函数执行流程及函数延续点问题的研究
    boost::statechart研究报告
    lambda,std::function, 函数对象,bind的使用备忘
    将博客搬至CSDN
    Impala的分布式查询
    轻量级文本搜索引擎的后台设计、实现与优化
    1 producer — n consumers 模型 实现
    1001. A+B Format (20)
  • 原文地址:https://www.cnblogs.com/hrnn/p/13413245.html
Copyright © 2011-2022 走看看