给定一个未排序的整数数组 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 <=
1
0
5
10^5
105
-
1
0
9
10^9
109 <= nums[i] <=
1
0
9
10^9
109
考虑枚举:x,看看它有没有x+1,x+2,x+3…
在枚举的过程中,如果枚举了x其实就不用枚举x+1,x+2,x+3…,因为不是最长的。
考虑在枚举的时候,取到的x,不存在x-1,即没有前驱的数。(哈希判断有没有前驱数,再逐个枚举)
class Solution {
public int longestConsecutive(int[] nums) {
// 去重
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longesLength = 0;
for (int num : num_set) {
// set 中没有 num-1,说明不构成连续子序列
if (!num_set.contains(num - 1)) {
int currentNum = num;
int currentLength = 1;
//枚举当前这个数(没有前驱),x能+到几就是多长
while (num_set.contains(currentNum + 1)) {
currentNum += 1;
currentLength += 1;
}
// 每找到一个数(没有前驱),更新最长的
longesLength = Math.max(longesLength, currentLength);
}
}
return longesLength;
}
}