题目说明
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
最长序列: 0 1 2 3 4 5 6 7 8, 序列长度 9
输出:9
代码
public class Q03_Solution {
public static void main(String[] args) {
int[] nums = {0,3,7,2,5,8,4,6,0,1};
System.out.println(longestConsecutive(nums)); // 9
int[] nums2 = {0,1,0,1};
System.out.println(longestConsecutive(nums2)); // 2
}
public static int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
if(nums.length == 1){
return 1;
}
// 排个序
Arrays.sort(nums);
// flag用于记录每次计算出的局部最长序列长度
int flag = 1;
// maxLength用于记录全局最长序列长度
int maxLength = 1;
for (int i = 0; i < nums.length - 1; i++) {
// 前后相差 1 , 局部最长序列长度 + 1;
if((nums[i+1] - nums[i]) == 1){
flag++;
} else if(nums[i] != nums[i + 1]){ // 前后不相等, 局部最长序列长度 从新赋值为1;
flag = 1;
}
// 取二者大的那个作为新的全局最长序列长度
maxLength = Math.max(flag,maxLength);
}
return maxLength;
}
}
结果