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.
借鉴网上的做法,因为limitation在O(n),所以考虑用hashmap
public int longestConsecutive(int[] num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(num.length==0)
return 0;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<num.length;i++)
map.put(num[i],1);
int max = 0;
for(int i=0; i<num.length;i++){
int cnt = 1;
int smaller = num[i]-1, larger = num[i]+1;
while(map.containsKey(smaller)){
cnt+=1;
map.remove(smaller);
smaller--;
}
while(map.containsKey(larger)){
cnt+=1;
map.remove(larger);
larger++;
}
max = Math.max(max,cnt);
}
return max;
}