最长连续序列

最长连续序列

题目

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

思路

  • 1、找到最小的num值
  • 2、while循环找连续的元素集合
  • 3、动态输出最长的

代码

def longestConsecutive(nums):
        if len(nums) <= 1:
            return len(nums)
        nums_set = set(nums)
        ans = 1
        for num in nums_set:
        # 任何一种排序序列都有开头的最小的值,[100,4,200,1,3,2]为例,100是一个序列,200是一个序列,1也是;
            if num - 1 not in nums_set:
                cur_num = num
                temp_length = 1
                while cur_num + 1 in nums_set:
                    cur_num = cur_num + 1
                    temp_length += 1
                # 100以及200序列while循环完temp_length为1;1开头的序列while循环完为4
                ans = max(ans, temp_length)
        return ans

验证

if __name__ == "main":
	nums = [100,4,200,1,3,2]
	ans = longestConsecutive(nums)
	# ans值为4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值