2.1.6 Longest Consecutive Sequence
描述Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, Given [100, 4, 200, 1, 3, 2], longest consecutive elements sequence is [1,2, 3, 4]. Return its length: 4.Your algorithm should run in O(n) complexity.
public static int solution2_1_6(int num[]){
if(num.length==0)
return 0;
if(num.length==1)
return 1;
else{
HashSet<Integer> tempSet=new HashSet<Integer>();
for(int i=0;i<num.length;i++)
tempSet.add(num[i]);
int maxLen=1;
for(int i=0;i<num.length;i++){
int tempLen=1;
int temp=num[i]+1;
while(tempSet.contains(temp)){//对于HashSet可以在O(1)的时间复杂度内判断是否存在该元素
tempSet.remove(temp);
tempLen++;
temp++;
}
temp=num[i]-1;
while(tempSet.contains(temp)){
tempSet.remove(temp);
tempLen++;
temp--;
}
if(tempLen>maxLen)
maxLen=tempLen;
if(tempLen>num.length)
break;
}
return maxLen;
}
}