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;
        }
        
    };

  • 相关阅读:
    【zookeeper】
    关于redis-windows环境下的一些配置:
    mybatis-注解开发
    jQuery的Validate插件
    Thymeleaf 学习笔记-实例demo(中文教程)
    thymeleaf 学习笔记-基础篇(中文教程)
    AGC 043C
    JOISC 2020 部分题解
    Loj #2687
    CF 1270I
  • 原文地址:https://www.cnblogs.com/hrnn/p/13413245.html
Copyright © 2011-2022 走看看