力扣 128. 最长连续序列

题目说明

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

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

提示:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

示例

示例 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

笔者理解

此题是一道数组算法问题,在力扣题库中被定义为中等题。

解法

当笔者阅读完此题后,使用了HashSet来存储数组中数,利用他的contains方法来判断当前元素是否有后继,让我们来看看具体如何实现的吧。

实现

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
class Solution {
/**
* HashSet
* 向后延展
*/
public int longestConsecutive(int[] nums) {
// 其一是利用set的contains方法,也可以避免出现重复数值
HashSet<Integer> set = new HashSet<Integer>();
for (int num : nums) {
set.add(num);
}

int result = 0;

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

// 向后延展寻找是否有后继
while (set.contains(currentNum + 1)) {
currentNum += 1;
currentLen += 1;
}

result = Math.max(result, currentLen);
}
}

return result;
}
}

时间和空间效率还行,可见此解法还比较适合此题。

image-20211117164251562

总结

本题是今天的一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。