LeetCode-128. Longest Consecutive Sequence-python3代码+解题思路

14 篇文章 0 订阅
3 篇文章 0 订阅

0.原题:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

翻译:在给定的未排序的、元素为整数的数组中,找出元素值连续的序列,输出最长的序列长度。要求O(n)复杂度。

 

1.代码:

class Solution:
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        list_length = len(nums)
        if(not list_length):
            return 0
        counters = []
        while(list_length):
            archor = nums.pop()
            counter = 1
            #look forward
            target = archor - 1
            while(target in nums):
                counter = counter + 1
                nums.remove(target)
                target = target - 1
            #look backward
            target = archor + 1
            while(target in nums):
                counter = counter + 1
                nums.remove(target)
                target = target + 1
            counters.append(counter)
            list_length = list_length - counter
        return max(counters)
    

 

2.思路:

(1)首先需要判断list是否为空。

这一步是必须的,否则max()函数对空列表求值会报错。另外,由于if判断和while循环都用到了nums列表的长度,所以的设置一个参数记录这一值,即list_length = len(nums)。

注意,不要在while循环中反复计算nums列表长度,即while(len(nums)),这样会增加计算量,最终程序会因超时无法通过。

(2)读入一个元素,并判断在nums中,与这个元素相邻元素的个数。

step1:从nums中弹出一个值,记为anchor;

step2:不断地向前找连续的值,即是否存在anchor-1,anchor-2,anchor-3……,找到一个,counter就+1,直到找不到连续的值为之;

step3:向后找连续的值,并做counter+1操作。最后,把counter值记录下来。

在寻找的过程中,为了减少重复操作,对于查找完的值,要及时从nums中删除。

(3)找出最长连续序列的长度

由于每一步的counter值都记录在counters中,所以只要求解max(counters),即可得到最终解。

 

3.LeetCode结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值