题目
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
思路
- 1、找到最小的num值
- 2、while循环找连续的元素集合
- 3、动态输出最长的
代码
def longestConsecutive(nums):
if len(nums) <= 1:
return len(nums)
nums_set = set(nums)
ans = 1
for num in nums_set:
# 任何一种排序序列都有开头的最小的值,[100,4,200,1,3,2]为例,100是一个序列,200是一个序列,1也是;
if num - 1 not in nums_set:
cur_num = num
temp_length = 1
while cur_num + 1 in nums_set:
cur_num = cur_num + 1
temp_length += 1
# 100以及200序列while循环完temp_length为1;1开头的序列while循环完为4
ans = max(ans, temp_length)
return ans
验证
if __name__ == "main":
nums = [100,4,200,1,3,2]
ans = longestConsecutive(nums)
# ans值为4