力扣刷题Day 23:最长连续序列(128)
1.题目描述
2.思路
暴力解法是会超出时间限制的。首先将nums写成一个集合(哈希表),无限循环,对于集合顶端的元素向左and向右扩展最大长度,每访问一个元素就把它从集合里删掉,循环的结束条件是集合为空。
3.代码(Python3)
class Solution:def longestConsecutive(self, nums: List[int]) -> int:def neighbor_exist(num):left_num, right_num = num - 1, num + 1current_consecutive = 1while 1:if left_num in nums_set:nums_set.remove(left_num)current_consecutive += 1left_num -= 1else:breakwhile 1:if right_num in nums_set:nums_set.remove(right_num)current_consecutive += 1right_num += 1else:breakreturn current_consecutivenums_set = set(nums)longest_consecutive = 0while 1:if len(nums_set) == 0:return longest_consecutivecurrent_consecutive = neighbor_exist(nums_set.pop())longest_consecutive = max(longest_consecutive, current_consecutive)
4.执行情况
5.感想
看了官方题解发现了更简便的代码,直接遍历集合,如果当前元素不是当前序列的开始元素就continue,如果是就扩展长度直到扩展不了,如下:
class Solution:def longestConsecutive(self, nums: List[int]) -> int:nums_set = set(nums)longest_consecutive = 0for num in nums_set:if (num - 1) not in nums_set:current_consecutive = 1current_num = numwhile (current_num + 1) in nums_set:current_consecutive += 1current_num += 1longest_consecutive = max(longest_consecutive, current_consecutive)return longest_consecutive
但是这个代码执行出来的效果竟然不如我上面写的那个。不过也确实,官方题解是把全部元素都判断了一遍是不是开头,我是用完就删,确实应该相对高效。