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
.
public class Solution {
public int longestConsecutive(int[] nums) {
HashSet hs = new HashSet();
for(int i : nums) {
hs.add(i);
}
int max = 0;
for(int i : nums) {
int cnt = 1;
hs.remove(i);
int tmp = i;
while(hs.contains(tmp-1)) {
hs.remove(tmp-1);
tmp--;
cnt++;
}
tmp = i;
while(hs.contains(tmp+1)) {
hs.remove(tmp+1);
tmp++;
cnt++;
}
max = Math.max(max, cnt);
}
return max;
}
}