LeetCode 128. 最长连续序列
一、题目详情
原题链接:128. 最长连续序列
给定一个未排序的整数数组 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
提示:
0 <= nums.length <= 104
-109 <= nums[i] <= 109
二、排序法
本题可以先将数组进行排序,然后对排序后的数组进行循环遍历,计算连续序列的最大长度。但这种方法会破坏数组的结构。
class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length == 0 || nums == null){
return 0;
}
Arrays.sort(nums);
//定义最大连续序列长度
int maxLength = 1;
//定义当前连续序列长度
int curLength = 1;
for(int i = 0;i < nums.length - 1;i++){
if(nums[i + 1] - 1 == nums[i]){
//当nums[i]和nums[i + 1]连续时,当前连续序列长度+1
curLength++;
}else if(nums[i + 1] == nums[i]){
//当nums[i]和nums[i + 1]相等时,跳出该次循环进行下次循环
continue;
}
else{
//当不连续时重置当前连续序列长度为1
curLength = 1;
}
//更新最大连续序列长度
maxLength = Math.max(maxLength,curLength);
}
return maxLength;
}
}
-----------------------------
时间复杂度:O(nlog(n))
空间复杂度:O(1)
三、哈希表法
class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length == 0 || nums == null){
return 0;
}
Set<Integer> set = new HashSet<>();
for(int i = 0;i < nums.length;i++){
set.add(nums[i]);
}
//定义最大连续序列长度
int maxLength = 1;
for(int num : set){
if(set.contains(num - 1)){
//当num不是左边界时,跳出此次循环执行下次循环
continue;
}else{
//定义当前连续序列长度
int curLength = 1;
while(set.contains(num + 1)){
//当连续时更新
curLength++;
num++;
}
//更新最大连续序列长度
maxLength = Math.max(maxLength,curLength);
}
}
return maxLength;
}
}