zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第128题:给定一个未排序的整数数组,找出最长连续序列的长度。 要求算法的时间复杂度为 O(n)。

    题目:
    给定一个未排序的整数数组,找出最长连续序列的长度。  要求算法的时间复杂度为 O(n)。
    思路:
    要求的时间复杂度为O(n),则只允许一次循环。
    程序:
    class Solution:
        def longestConsecutive(self, nums: List[int]) -> int:
            nums.sort()
            length = len(nums)
            if length <= 0:
                return 0
            if length == 1:
                return 1
            max_count = 1
            counter = 1
            for index in range(1,length):
                if nums[index - 1] == nums[index]:
                    continue
                if nums[index - 1] < nums[index] and nums[index] - nums[index - 1] == 1:
                    counter += 1
                    max_count = max(max_count, counter)
                else:
                    counter = 1
                    continue
            return max_count
  • 相关阅读:
    hdu5249
    hdu5673-Robot
    hihoCoder 1033
    simpleOS 1.0
    hdu3511-Prison Break
    单调栈
    关于每次取PC的值为PC+4的问题
    hdu3652
    Linux MySQL5.7.18安装手册
    Linux MySQL5.6.36安装手册
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12767205.html
Copyright © 2011-2022 走看看