1. 程式人生 > >Longest Consecutive Sequence

Longest Consecutive Sequence

best num clas while algorithm 整數 連續序列 problem its

  Nov, 9, 2017.
  https://leetcode.com/problemset/algorithms/?topicSlugs=union-find%2Clinked-list
  Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
  For example,
  Given [100, 4, 200, 1, 3, 2],
  The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
  Your algorithm should run in O(n) complexity.

  建立字典,依次讀入整數,每次在邊界處記錄長度變化,為防止重復計算,整數必須被讀入字典。

  復雜度為O(N),以下是submission。

 1 class Solution:
 2     def longestConsecutive(self, nums):
 3         length = {}
 4         ans = 0
 5         for i in nums:
 6             if i not in length:
 7                 l = length[i - 1] if i - 1 in length else 0
8 r = length[i + 1] if i + 1 in length else 0 9 length[i] = length[i - l] = length[i + r] = l + r + 1 10 ans = max(ans, length[i]) 11 return ans

  解法二,數組->哈希表,尋找連續序列起始數(x-1 not in nums),直接查找這個序列的長度。

  有趣的地方在於,我們是在哈希表裏查詢一個確定的數,使得這個操作的復雜度被壓進了O(1)。因此這個算法的復雜度還是O(N)。

  以下是StefanPochmann的submission。

 1 def longestConsecutive(self, nums):
 2     nums = set(nums)
 3     best = 0
 4     for x in nums:
 5         if x - 1 not in nums:
 6             y = x + 1
 7             while y in nums:
 8                 y += 1
 9             best = max(best, y - x)
10     return best

  其實兩種方法都利用了哈希表查詢的便利性。我原來想把輸入看作森林,用並查集來完成工作。這種算法不好實現,也不見得簡單。

Longest Consecutive Sequence