给定一个无序的整数类型数组,求最长的连续元素序列的长度。
例如:
给出的数组为[100, 4, 200, 1, 3, 2],
最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4
你需要给出时间复杂度在O(n)之内的算法
import java.util.*;
public class Solution {
/**
*
* @param num int整型一维数组
* @return int整型
*/
public int longestConsecutive (int[] num) {
// write code here
Arrays.sort(num);
int len = 1;
int max = 1;
if(num == null || num.length == 0){
return 0;
}
if(num.length == 1){
return 1;
}
int i = 0;
for (; i < num.length - 1; i++) {
if(num[i] + 1 == num[i + 1]){
len++;
}else if (num[i] == num[i + 1]) {
continue;
}else {
if (len > max) {
max = len;
}
len = 1;
}
}
if(i == num.length - 1 && len > max){
max = len;
}
return max;
}
}