1 题目描述
给定一个无序的整数类型数组,求最长的连续元素序列的长度。
例如:
给出的数组为[1000, 4, 2000, 1, 3, 2],
最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
你需要给出时间复杂度在O(n)之内的算法
2 解题思路
代码
3 代码实现
import java.util.*;
public class Solution {
/**
*
* @param num int整型一维数组
* @return int整型
*/
public int longestConsecutive (int[] num) {
// write code here
Set<Integer> set = new HashSet<Integer>();
for(int n : num)
set.add(n);
int max = 1;
for(int n : num){
if(set.remove(n)){
int val = n;
int tmp = 1;
int val_small = val - 1;
int val_large = val + 1;
while(set.remove(val_small)){
tmp++;
val_small--;
}
while(set.remove(val_large)){
sum++;
val_large++;
}
max = Math.max(max, tmp);
}
}
return max;
}
}
4 运行结果
运行时间:71ms
占用内存:13368k