128. 最长连续序列(中等)

1,问题描述

128. 最长连续序列

难度:中等

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

示例 1:

1
2
3
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。

示例 2:

1
2
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9

示例 3:

1
2
输入:nums = [1,0,1,2]
输出:3

提示:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109

2,初步思考

​ 官方的解法最优!我也是看了之后受到启发

3,代码处理

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.*;

public class _128最长连续序列 {

// 直接排序使用双指针处理
// public int longestConsecutive_sort(int[] nums) {
// if (nums.length <= 1) return nums.length;
// Arrays.sort(nums);
// int l = 0, r = 1, max = 0;
// while (l < r && r < nums.length) {
// if (nums[l] == nums[r]) {
// r++;
// l++;
// }
// }
// return max;
// }

// 我最开始想到的解法是:set去重,最大堆逐个取出并且监控连续性,但是这样不符合实际复杂度O(n)
public int longestConsecutive_brute(int[] nums) {
if (nums.length <= 1) return nums.length;
Set<Integer> set = new HashSet<>();
List<Integer> list = new ArrayList<>();
for (int num : nums) {
if (set.add(num)) {
list.add(num);
}
}
Collections.sort(list);

// 双指针
int l = 0, r = 1, max = 0;
while (l < r && r < list.size()) {
if (list.get(r) - list.get(l) == r - l) {
max = Math.max(max, r - l + 1);
r++;
} else {
l = r;
r++;
}
}
return max;
}

// 看完官方解法的知道的解法
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int max = 0;
for (Integer num : set) {
int counter = 1;
if (!set.contains(num - 1)) {
int index = num;
while (set.contains(index + 1)) {
index++;
counter++;
}
}
max = Math.max(max, counter);
}
return max;
}

public static void main(String[] args) {
_128最长连续序列 longestConsecutive = new _128最长连续序列();
// System.out.println(longestConsecutive.longestConsecutive(new int[]{100, 4, 200, 1, 3, 2}));
// System.out.println(longestConsecutive.longestConsecutive_brute(new int[]{100, 4, 200, 1, 3, 2}));
System.out.println(longestConsecutive.longestConsecutive_brute(new int[]{0}));
}
}

4,官方题解

方法一:哈希表

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
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}

int longestStreak = 0;

for (int num : num_set) {
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;

while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}

longestStreak = Math.max(longestStreak, currentStreak);
}
}

return longestStreak;
}
}