Leetcode 128:最長連續序列(最詳細的解法!!!)
阿新 • • 發佈:2019-01-01
給定一個未排序的整數陣列,找出最長連續序列的長度。
要求演算法的時間複雜度為 O(n)。
示例:
輸入: [100, 4, 200, 1, 3, 2]
輸出: 4
解釋: 最長連續序列是 [1, 2, 3, 4]。它的長度為 4。
解題思路
對於這個問題首先可以想到的解法就是先排序,然後遍歷排序後的陣列,找出最長的連續陣列。這裡有一個陷阱,我們在排序之前需要去重。
class Solution:
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
nums = list(set(nums))
nums.sort()
res, i, nums_len = 1, 0, len(nums)
while i < nums_len - 1:
tmp = 1
while i < nums_len - 1 and nums[i] == nums[i+1] - 1:
tmp += 1
i += 1
res = max(res, tmp)
i += 1
return res
這種解法當然很垃圾,很明顯題目的要求(O(n)
複雜度)不是要我們這樣去做。怎麼辦呢?可以這樣做,首先通過set
將nums
去重並且hash
。然後我們遍歷nums
中的元素x
,先判斷x-1
是不是在nums
中(也就是先確定連續陣列的最小值),如果不在的話,我們接著判斷x+1
是不是在nums
中,接著判斷x+2
是不是在nums
中,類推下去。這樣我們就可以找到最長的連續陣列。
class Solution :
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = set(nums)
best = 0
for x in nums:
if x - 1 not in nums:
y = x + 1
while y in nums:
y += 1
best = max(best, y - x)
return best
但是實際測試的時候上面的這個做法比第一個慢。
reference:
我將該問題的其他語言版本新增到了我的GitHub Leetcode
如有問題,希望大家指出!!!