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.
public class Solution {
public int longestConsecutive(int[] num) {
if(num == null || num.length == 0) return 0;
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < num.length; i++){
set.add(num[i]);
}
int max = 0;
for(int i = 0; i < num.length; i++){
if(set.contains(num[i])){
int current = num[i];
int length = 1;
set.remove(current++);
while(set.contains(current)){
length++;
set.remove(current++);
}
current = num[i] - 1;
while(set.contains(current)){
length++;
set.remove(current--);
}
max = Math.max(max, length);
}
}
return max;
}
}