思路1:先将nums排序(利用sort方法或sorted函数),再遍历nums找出最长连续序列的长度
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 特殊情况:当nums为空数组
if len(nums)==0:
return 0
# nums数组排序(从小到大)
lst=sorted(nums)
temp_len=1
answer_len=0
temp=lst[0]
for i in lst:
# 若当前元素==上一个元素(temp),跳过
if i==temp:
continue
else:
# 若当前元素与上一个元素的差值为1
if i-temp==1:
temp_len+=1
# 差值超过1,即当前元素与上一序列并非连续
else:
if temp_len>answer_len:
answer_len=temp_len
else:
pass
temp_len=1
temp=i
# 跳出循环,最后一次比较&赋值
if temp_len>answer_len:
answer_len=temp_len
else:
pass
return answer_len
①list.sort方法是Python的列表方法,用于对原列表进行排序。list.sort方法没有任何返回值。
list.sort(key=function, reverse=boolean)
返回值:None
⚠️注意:函数在原有列表上直接排序,因此该方法使用完后原列表的顺序发生了改变。
而Python里的sort排序是一种名为 Timsort 的排序方法,其时间复杂度为O (n*logn),而且这是一种快速的稳定的排序方法。
②sorted()函数的基本语法格式如下:
list = sorted(iterable, key=None, reverse=False)
思路二:先利用set()函数将列表转换为集合(去除重复元素),再逐一遍历元素,判断该元素是否为某一连续序列的start,再往上依次寻找数值是否出现在集合中。
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
longest_streak = 0
# 数组列表转换为集合
num_set = set(nums)
for num in num_set:
# 当该元素为某一连续序列的start时
if num - 1 not in num_set:
current_num = num
current_streak = 1
# 用while循环往上依次寻找数值是否出现在集合中
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
longest_streak = max(longest_streak, current_streak)
return longest_streak
①set()函数将列表转换为集合,清除相同元素。
②set集合数据类型是不可索引的,但是可迭代的!
思路三:哈希表
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
res = 0
hash_dict = dict()
for num in nums:
# 新进来哈希表一个数
if num not in hash_dict:
# 获取当前数的最左边连续长度,没有的话就更新为0
left = hash_dict.get(num-1,0)
# 同理获取右边的数
right = hash_dict.get(num+1,0)
# 把当前数加入哈希表,代表当前数字出现过
hash_dict[num] = 1
# 更新长度
length = left+1+right
res = max(res,length)
# 更新最左端点的值
hash_dict[num-left] = length
# 更新最右端点的值
hash_dict[num+right] = length
# 此时 【num-left,num-right】范围的值都连续存在哈希表中了
return res
关键问题:为什么要将length同时赋给最左端的点和最右端的点?
因为要保证下一个元素无论从哪一端接入该序列时,都可以立即知道当前序列的长度。