简繁EN

LeetCodeNo. 095

[LeetCode with Python] 128. Longest Consecutive Sequence

Contents

Problem

Problem page: https://leetcode.com/problems/longest-consecutive-sequence/
Topics: Array
Difficulty: 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.


Analysis

Given a sequence of ints that isn't necessarily sorted, find numbers in it that form a new sequence. The numbers have to be consecutive, and the new sequence should be as long as possible.
The most obvious approach is to sort the original sequence and then go through it once to find the longest consecutive sequence. The time complexity is O(nlogn)+O(n)=O(nlog(n)), so it doesn't meet the problem's O(n) requirement (by the way, does the original problem mean O(n) time complexity only, or does it require O(n) for both time complexity and space complexity? I'm guessing it's the latter). So I use a hash table. First I go through the original sequence and insert each element into the hash table with the element itself as the key and True as the value. Then I can go through each element in the hash table and search in both directions, checking whether the next consecutive number is in the hash table, to find the longest consecutive sequence. I also set the value of each element I've searched to False so I don't repeat the search for elements in a consecutive sequence I've already searched.
Space complexity is O(n). Time complexity is O(n). Python implements its dictionaries with hash tables, so for now I just use a dictionary for the hash table here.
Be careful not to repeat the search for other elements in the same consecutive sequence.
All in all, this algorithm is pretty hard to think of. Sorting and then going through the sequence is more intuitive and might be the first thing that comes to mind.


Code

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

Article link: https://xnerv.wang/en/leetcode-longest-consecutive-sequence/