Problem Summary
Given an unsorted array of integers, A[1], A[2],…, A[N], find the length of the longest consecutive elements sequence.
Solution 1
We can sort the array first, and iterate through it.
This takes O(NlogN) time but does not need extra space.
Solution 2
Unordered set or hash table can help us to achieve a better time complexity of O(N).
First, we put all integers in the array in an unordered set (or a hash table).
Second, we iterate through the given array. For each A[i], we calculate the maximal r such that A[i],A[i]+1,A[i]+2,…,A[i]+r are all in the set, the maximal l such that A[i],A[i]-1,A[i]-2,…,A[i]-l are all in the set. Then we update the answer with l+r+1, and erase A[i]-l,A[i]-l+1,…,A[i],A[i]+1,…,A[i]+r from the set.
The time and space complexity are both O(N).
Code for Solution 2
|
|