给定一个未排序的整数数组 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]
输出: 9
示例 3:
输入: nums = [1,0,1,2]
输出: 3
-
分析题目
题目是要我们的从数组里面的找到连续的数组 什么是连续的数字就是 1 2 3 4 这种等差数列公差是是1的 连续数字
-
第一种做法暴力解法
我们可以用2层for 循环嵌套让相邻的2个数做差 求差 然后判断是否等1 但是这种做法是运算时间复杂度是0(n*n) 虽然也能解出来但是不符合题意
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int maxLength = 0;
// 外层循环遍历每个元素作为起点
for (int i = 0; i < nums.length; i++) {
int currentNum = nums[i];
int currentLength = 1;
// 内层循环尝试扩展连续序列
for (int j = 0; j < nums.length; j++) {
if (nums[j] - currentNum == 1) {
currentNum++; // 找到下一个连续数字
currentLength++;
j = -1; // 重置 j,重新从头查找下一个连续数字
}
}
// 更新最长连续序列长度
maxLength = Math.max(maxLength, currentLength);
}
return maxLength;
}
-
测试用例
public static void main(String[] args) {
int[] nums = {100,4,200,1,3,6,4,5};
System.out.println(new Leetcode().longestConsecutive(nums));
}
-
方法二 使用HashSet
我们首先需要将我们的 数组循环遍历到我们添加到我们HashSet 集合里面来了 然后判断set 里面包含我们起点的连续数字 并且+1 存在的时候我们 length+1 最终使用 maxLength 更新最大长度
// 更新最大长度
maxLength = Math.max(maxLength, currentLength);
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
// 使用 HashSet 存储所有数字,去重并支持快速查找
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
int maxLength = 0;
// 遍历数组中的每一个数字
for (int num : numSet) {
// 只有当当前数字是连续序列的起点时才进行扩展
if (!numSet.contains(num - 1)) {
int currentNum = num;
int currentLength = 1;
// 向后扩展连续序列
while (numSet.contains(currentNum + 1)) {
currentNum += 1;
currentLength += 1;
}
// 更新最大长度
maxLength = Math.max(maxLength, currentLength);
}
}
return maxLength;
}
-
测试用例