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
  • 相关阅读:
    大厂的面试官是如何挑人的?
    搞懂这7个Maven问题,带你吊打面试官!
    Spring Cloud Eureka 注册安全一定要做到位!
    09 webpack的介绍
    08 node.js 的使用
    07 Node.js安装及环境配置
    06-Nodejs介绍
    05-面向对象
    Mysql 的使用方法
    04-对象的单体模式
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12767205.html
Copyright © 2011-2022 走看看