rt,其实挺简单的一个题,但是一些细节的处理上就是不如答案好,复杂度就是比他高。
我的思路是:构建哈希表path,然后对于每个数字num,如果前一个数如果在数组中,那么它就等于path[num - 1] + 1。然后一个循环,如果它后面的数在数组中,就一直path[next] = path[next - 1] + 1,但还是超时。
仔细想想确实,你这样做会引起不必要的更新。比如100,101在前面,已经被搜过一次了,后面遇到99,又要对他们再次更新,很浪费,真不如答案那么直截了当,非常节约。
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
longest_streak = 0
num_set = set(nums)
for num in num_set:
if num - 1 not in num_set: #是起点,可以搜
current_num = num
current_streak = 1
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
longest_streak = max(longest_streak, current_streak)
return longest_streak