leetcode128

本文详细解析了一种求解最长连续序列的算法实现,通过将输入整数数组进行排序和去重,然后遍历数组比较相邻元素,计算并返回最长连续序列的长度。此算法适用于寻找整数数组中最长连续子序列的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 class Solution:
 2     def longestConsecutive(self, nums: 'List[int]') -> int:
 3         if len(nums)<=1:
 4             return len(nums)
 5 
 6         nums2 = sorted(set(nums))
 7         pre = nums2[0]
 8         maxc = 0
 9         curc = 1
10         for i in range(1,len(nums2)):
11             if nums2[i] == pre + 1:
12                 curc += 1
13             else:
14                 maxc = max(maxc,curc)
15                 curc = 1
16             pre = nums2[i]
17         return max(maxc,curc)

 

转载于:https://www.cnblogs.com/asenyang/p/10472795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值