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
  • 相关阅读:
    P1880 [NOI1995]石子合并
    LC 1388. Pizza With 3n Slices
    1129 Recommendation System
    1131 Subway Map
    C#中的lamda实用的select用法
    C# Image与Base64编码互转函数
    签名算法的URL
    xml格式封装数据
    layer 相关网址
    js-清空array数组
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12767205.html
Copyright © 2011-2022 走看看