题目描述
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
样例描述
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
思路
哈希表
- 将所有数放进哈希表,只枚举每一段的最小值(比如枚举x的时候,保证x存在且x - 1不存在),然后依次枚举后面的数是否存在。(由于不清楚序列的长度有多少,应该用while来枚举后面的序列)
- 避免重复,保证每个数只枚举一次,枚举完就删掉。

代码
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num : nums) set.add(num);
int res = 0;
for (int x: nums) {
int y = x;
if (set.contains(x) && !set.contains(x - 1)) {
set.remove(x);
//寻找序列长度,不清楚有多少个 所以用while
while (set.contains(y + 1)) {
y ++;
set.remove(y);
}
res = Math.max(res, y - x + 1);
}
}
return res;
}
}
版权声明:本文为Sherlock_Obama原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。