Leetcode Hot 100最长连续序列
题目描述
思路
思路1
我们对数组进行排序,通过遍历数组,如果前一个数组的值+1等于当前数组的值,计数count++,如果中断了,计算当前最大连续长度的值ans,并且统计值count重新置为1,最后返回count与ans的最大值
class Solution:def longestConsecutive(self, nums: List[int]) -> int:if not nums:return 0count=1ans=0nums.sort() #排序n=len(nums)for i in range(1,n):if nums[i]==nums[i-1]: #重复的跳过continueelif nums[i]==nums[i-1]+1:count+=1else:ans=max(ans,count)count=1# 中断的时候需要重新置1return max(count,ans)
思路2
不需要排序,通过哈希集合,遍历数组来判断每个数是否为连续序列开头的那个数
class Solution:def longestConsecutive(self, nums: List[int]) -> int:length=0num_set=set(nums)for num in num_set:if num-1 not in num_set:# 检查开头cur=numcur_lenth=1while cur+1 in num_set:cur+=1cur_lenth+=1length=max(length,cur_lenth)return length