Problem Link:
http://oj.leetcode.com/problems/longest-consecutive-sequence/
This problem is a classical problem where we can reduce the running time by
the help of hash table.
By given a list of numbers, we can find the longest consecutive sequence by
the following steps:
- Let H be a empty hash set, add all given numbers into H (duplicates will
be removed) - Let max_len = 0 denote the length of current longest consecutive
sequence - While H is not empty:
- count all n‘s smaller consecutive numbers in H and remove them from
H - count all n‘s larger consecutive numbers in H and remove them from
H - update max_len with the length of this consecutive sequence containing
n
- count all n‘s smaller consecutive numbers in H and remove them from
The python code is as follows.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
【LeetCode OJ】Longest Consecutive Sequence,布布扣,bubuko.com