题目描述
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
提示:
- 0 <= nums.length <= 10 ^5
- -10 ^9 <= nums[i] <= 10 ^9
解题思路
用哈希表去重。将不重复数字序列保存在哈希表的keys中。
该算法核心在于如何解决时间复杂度,即如何跳过不符合题目条件的循环。
如果以当前的数字x为序列起点,则表明x前面的数字一定不存在于去重数组中,即x-1不存在,则当前x为序列起点,依次枚举x+1,x+2…x+y…x+n-1,其中n为原列表去重后的长度,分别与keys匹配,更新答案。每次枚举结束后,与上一次的序列长度对比,取最大值。若x-1存在,这可以作为判断跳过循环的条件,表示当前列表中存在比x小的数,因此直接跳过。
代码实现
def longestConsecutive(self, nums: List[int]) -> int:
my_hash = {}
for num in nums:
if num not in my_hash:
my_hash[num] = 1
# 若列表为空,直接返回
if len(nums)==0:
return 0
res = 0
for x in my_hash.keys():
# 若当前x-1不存在,说明x为序列起点
if x-1 not in my_hash:
current_x = x
length = 1
# 枚举匹配,直到超出原列表数字范围
while (current_x+1) in my_hash.keys():
current_x+=1
length+=1
# 取最大值
res = max(length,res)
return res