题目描述:
给定一个无序的整数类型数组,求最长的连续元素序列的长度。
例如:
给出的数组为[100, 4, 200, 1, 3, 2],
最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
你需要给出时间复杂度在O(n)之内的算法
解题思路:
- 这里利用 set 集合里不能存储重复元素的特性
- 以及利用 set.remove 方法返回 true 后者 false 来判断当前集合是否含有该元素
代码如下:
public int longestConsecutive(int[] num) {
if(num == null || num.length == 0) return 0;
// 将当前数组内的元素存入集合中
Set<Integer> set = new HashSet<>();
for(int item : num) set.add(item);
// 判断当前元素在 set 集中是否存在,若存在,继续向前和向后遍历元素
int res = 0;
for(int item: num){
if(set.remove(item)){
int pre = item - 1;
int pos = item + 1;
while(set.remove(pre)) pre--;
while(set.remove(pos)) pos++;
res = Math.max(res,pos - pre - 1);
}
}
return res;
}