https://leetcode.cn/problems/longest-consecutive-sequence/
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 :
输入:nums = [100,4,200,1,3,2] 输出:4 解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
import java.util.*;
public class hot128 {
/**
* 找出数组中最长连续序列的长度
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*
* @param nums 未排序的整数数组
* @return 最长连续序列的长度
*/
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
// 将所有数字放入 HashSet 中,实现 O(1) 查找
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
int maxLength = 0;
// 遍历每个数字
for (int num : numSet) {
// 只有当 num-1 不存在时,num 才是一个序列的起点
if (!numSet.contains(num - 1)) {
int currentNum = num;
int currentLength = 1;
// 向后查找连续的数字
while (numSet.contains(currentNum + 1)) {
currentNum++;
currentLength++;
}
// 更新最大长度
maxLength = Math.max(maxLength, currentLength);
}
}
return maxLength;
}
public int longestConsecutive2(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
HashSet<Integer> numSet = new HashSet<>();
for (int num : nums) {
numSet.add(num);
}
int maxLen = 0;
for (int num : numSet) {
if (!numSet.contains(num - 1)){
int curNum = num;
int ans = 1;
while(numSet.contains(curNum + 1)){
ans++;
curNum++;
}
maxLen = Math.max(maxLen, ans);
}
}
return maxLen;
}
}
289

被折叠的 条评论
为什么被折叠?



