Problem
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 |
|
Explanation
- Since it’s O(n) complexity, so we use a set to store all the numbers. Then, we iterate the array’s number, if it is in the set, then we remove it from the set and create two variables
pre
andnex
to record its previous continuous number and next continuous number. Then, we find ifpre
in the set, if it is in the set, then we remove it from the set and update--pre
untilpre
is not in the set. Similar tonex
, if it is in the set, then we remove it and update++nex
untilnex
is not in the set. Now, the current number’s longest continuous sequence will benex-pre-1
.
Solution
1 |
|