動機
令人回想到73 如果找不到範圍就先看看怎麼定義頭吧
Problem
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
Example 1:
Input: nums = [100,4,200,1,3,2]Output: 4Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]Output: 9
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
Sol
用set去存所有數字不難,但是怎麼找出sequence就會頭痛了
會頭痛是因為不知道怎麼找出sequence的範圍,如果列舉每個數字去找最大長度,會有許多重複計算
如果是sequence會有頭與尾
那要找頭還是尾? 其實都可以,下面是找頭
這讓我想起73把第一行與列當成mark sheet來用
class Solution:
def longestConsecutive(self, nums):
nums = set(nums)
ret = 0
for n in nums:
if n-1 not in nums:
tmp = 1
while n+1 in nums:
n,tmp = n+1, tmp+1
ret = max(ret,tmp)
return ret