虽然是hard题,但没有设计难度,题目也没有亮点。
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
searchW={x:True for x in nums}
res=0
for n in nums:
if searchW[n]:
lc=rc=0
l=r=n
searchW[n]=False
while l-1 in searchW:
searchW[l-1]=False
l-=1
lc+=1
while r+1 in searchW:
searchW[r+1]=False
r+=1
rc+=1
res=max(res,lc+rc+1)
return res

本文介绍了一种解决最长连续序列问题的高效算法。通过使用字典记录数组元素,避免了重复搜索,实现了O(n)的时间复杂度。算法首先将所有元素标记在字典中,然后遍历每个元素,检查其左右相邻元素是否在字典中,同时更新最长连续序列的长度。
744

被折叠的 条评论
为什么被折叠?



