描述
给定一个未排序的整数数组,找出最长连续序列的长度。
您在真实的面试中是否遇到过这个题? 是
说明
要求你的算法复杂度为O(n)
样例
给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4
思路:
首先想到的肯定是排序,这题直接排序,然后遍历一遍就可以,但是这肯定不是想要的答案,
排序的话复杂度最低也是 O(nlgn)。
继续思考,我们是否可以使用HashMap讲这些数据保存起来,考虑到可能存在重复的数据,我们
先使用HashSet讲这些数据保存起来。
然后,遍历原数组,每次取出一个数,如果这个数的前一个,后一个在Set中,再依次向前,向后搜索,将这些遍历过的数
从Set删掉,计算得到此连续序列的长度,跟历史搜索过的最大长度相比较,更新。
Java实现代码:
public int longestConsecutive(int[] num) {
// write your code here
HashSet<Integer> set = new HashSet<>();
for(int i:num){
set.add(i);
}
int maxLength = 0;
for(int i=0;i<num.length;i++){
int down = num[i]-1;
while (set.contains(down)){
set.remove(down);
down--;
}
int up = num[i]+1;
while (set.contains(up)){
set.remove(up);
up++;
}
if((up-down)>maxLength){
maxLength = up-down-1;
}
}
return maxLength;
}