128. Longest Consecutive Sequence
Problem description:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:1
2
3Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Solution:
The idea is, when we have a number n
, check it’s n+1
and n-1
to get the maximum length, and erase them from the set. Because if they’re consecutive, only need to count once.
1 | class Solution { |
time complexity: $O(n)$
space complexity: $O(n)$
reference: