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
should be [1, 2, 3, 4]. Its length is 4.
Your algorithm should run in O(n) complexity.
将数组放入map中,向左右减一加一查找,查找过的数字直接跳过。
public int longestConsecutive(int[] nums) {
HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();
for(int i: nums)
hs.put(i, 0);
int maxl = 1;
for(int i: nums){
if (hs.get(i) == 1) continue;
int tmp = i;
int current_max = 1;
while(hs.containsKey(tmp+1)){
current_max ++;
tmp ++;
hs.put(tmp, 1);
}
tmp = i;
while(hs.containsKey(tmp-1)){
current_max ++;
tmp --;
hs.put(tmp, 1);
}
maxl = Math.max(current_max, maxl);
}
return maxl;
}