给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence
例:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
解析:
先去重,然后遍历数组,有比当前数字小的存在于数组中直接跳过,找寻序列中最小的那个,然后向上查找,存储查找到的最长序列长度并进行存储。
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
longest = 0 # 最长序列长度
nums = set(nums) # 去重
for num in nums: # 遍历数组
if num - 1 not in nums: # 只从序列中最小的那一个开始查询
now_num = num
now_long = 1 # 当前最长长度
while now_num + 1 in nums: # 查询
now_num += 1
now_long += 1
longest = max(longest, now_long) # 比较返回最大的那个
return longest # 返回最大值