zoukankan      html  css  js  c++  java
  • 一道算法-最长连续序列

    给定一个未排序的整数数组,找出最长连续序列的长度。

    要求算法的时间复杂度为 O(n)。

    示例:

    输入: [100, 4, 200, 1, 3, 2]
    输出: 4
    解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-consecutive-sequence
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution:
        def longestConsecutive(self, nums: List[int]) -> int:
            if not nums:
                return 0
            s = set(nums)
            maxlen = 0
            for num in s:
                cur_len = 1
                #取出set的最小值
                if num-1 in s:
                    continue
                while num+1 in s:
                    num = num+1
                    #计算当前的长度
                    cur_len+=1
                    #比较当前长度与之前
                maxlen = max(maxlen,cur_len)
            return maxlen
  • 相关阅读:
    A. Generous Kefa
    1031 骨牌覆盖
    1074 约瑟夫环 V2
    1073 约瑟夫环
    1562 玻璃切割
    Ants
    1024 矩阵中不重复的元素
    1014 X^2 Mod P
    1135 原根
    1010 只包含因子2 3 5的数
  • 原文地址:https://www.cnblogs.com/topass123/p/13053385.html
Copyright © 2011-2022 走看看