给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
思路:
方法1: 利用set集合
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int longestStreak = 0;
for (int num : set) {
if (!set.contains(num - 1)) {
int currentNum = num;
int currentN = 1;
while (set.contains(currentNum + 1)) {
currentNum += 1;
currentN += 1;
}
longestStreak = Math.max(longestStreak , currentN);
}
}
return longestStreak ;
}
时间复杂度:O(n)
空间复杂度:O(n)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)