给定一个未排序的整数数组 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 <= 105
-109 <= nums[i] <= 109
方法一
因为题目要求时间复杂度必须小于O(n),所以不能使用Arrays.sort()方法,因为Arrays.sort()使用的是快速排序算法,时间复杂度为nlog(n),所以通过提高空间复杂度来解决,使用Set对数组进行去重,遍历set,若当前数字在set中已经找不到比它刚好大1的数字,则遍历set,找到以该数字为结尾的最长连续序列,具体方法如下:
class Solution {
public int longestConsecutive(int[] nums) {
if (nums.length == 0) {
return 0;
}
Set<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
int res = 1;
for (int num : set) {
if(!set.contains(num + 1)) {
int count = 1;
int cur = num;
while(set.contains(num - 1)) {
count++;
num--;
}
res = Math.max(count, res);
}
}
return res;
}
}
同理,也可以利用set中没有当前数字-1的元素时,表明当前数字为某个连续序列的起点,然后再遍历set获取答案。