简繁EN

LeetCodeNo. 095

【LeetCode with Python】 128. Longest Consecutive Sequence

目錄

題目

原題頁面:https://leetcode.com/problems/longest-consecutive-sequence/
題目型別:Array
難度評價:Hard

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.


分析

給定一個不一定有序的int序列,從裡面找出一些能夠構成一個新序列的數字,要求這些數字是連續的,並且新序列能足夠長。
先對原序列排序,然後再遍歷一次找最長連續序列這種做法是最直觀的,時間複雜度是O(nlogn)+O(n)=O(nlog(n)),顯然不滿足本題要求O(n)複雜度的要求(話說原題要求的這個O(n)複雜度是僅指時間複雜度,還是同時要求時間複雜度和空間複雜度?估計是後者)。所以用一個hashmap,首先遍歷原序列,以每個元素值作為key,True作為value插入到hashmap中。然後就可以遍歷這個hashmap中的每個元素,試圖去搜索這個元素左右連續的元素是否存在於hashmap中,從而去找出最長的連續序列。同時注意將搜尋過的元素的Value置為False,避免對已經搜尋過的連續序列中的元素再重複搜尋。
空間複雜度O(n)。時間複雜度O(n)。由於Python中的字典就是用hash表實現的,因此這裡就暫用字典代替hash表。
注意避免重複搜尋同一連續序列中的其它元素。
總的來說這種演算法比較難想到,排序後再遍歷的演算法比較直觀,可能會在第一時間想到。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
# @param num, a list of integer
# @return an integer
def longestConsecutive(self, num):
hashmap = { }
for i in num:
hashmap[i] = True
max_n = 0
for k, v in hashmap.items():
if not v:
continue
left = k - 1
right = k + 1
while hashmap.has_key(left) and hashmap[left]:
hashmap[left] = False
left -= 1
while hashmap.has_key(right) and hashmap[right]:
hashmap[right] = False
right += 1
n = right - left - 1
if n > max_n:
max_n = n
return max_n

本文地址:https://xnerv.wang/zh-tw/leetcode-longest-consecutive-sequence/