128. 最长连续序列
2024-09-18 02:46:04 # LeetCode

给定一个未排序的整数数组 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

Solution 1

第一次尝试,使用深度优先搜索解答,失败,超时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> used;
List<Integer> temp;
int max = 0;
for (int num : nums) {
used = new HashSet<>(nums.length);
temp = new ArrayList<>();
temp.add(num);
used.add(num);
dfs(used, temp, nums);
if (temp.size() > max) {
max = temp.size();
}
if (used.size() == nums.length) {
break;
}
}
return max;
}

private void dfs(Set<Integer> used, List<Integer> temp, int[] nums) {
for (int num : nums) {
if (!used.contains(num) && !temp.contains(num)) {
boolean isContinues = false;
for (Integer x : temp) {
if (num == x + 1 || num == x - 1) {
isContinues = true;
break;
}
}
if (isContinues) {
temp.add(num);
used.add(num);
dfs(used, temp, nums);
}
}
}
}
}

Solution 2

官方解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> numSet = new HashSet<>(nums.length);
for (int num : nums) {
numSet.add(num);
}

int max = 0;
int len;
for (Integer num : numSet) {
if (!numSet.contains(num - 1)) {
len = 1;

while (numSet.contains(num + 1)) {
len++;
num++;
}

max = Math.max(len, max);
}
}
return max;
}
}
  • 执行用时:27 ms(击败 60.38% 使用 Java 的用户)
  • 内存消耗:60.79 MB(击败 75.79% 使用 Java 的用户)

Tips

因为要求连续,所以可以只管往后(大)遍历,如果 x - 1 是存在的就可以直接跳过,找出最前(小)的一个开始遍历,这样可以省下很多无效的遍历次数

Source

128. 最长连续序列