网站加网页,品牌网站升级,吉林企业建站系统费用,wordpress子目录网站给定一个未排序的整数数组 nums #xff0c;找出数字连续的最长序列#xff08;不要求序列元素在原数组中连续#xff09;的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1#xff1a;
输入#xff1a;nums [100,4,200,1,3,2] 输出#xff1a;4 …给定一个未排序的整数数组 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 Related Topics 并查集 数组 哈希表 public int longestConsecutive(int[] nums) {// 不存在num -1 就可以作为一个序列的开头// 不存在num 1 就可以作为一个序列的结尾// 计算长度int length 0;int maxLength 0;HashSetInteger hashSet new HashSetInteger();for (int num : nums) {hashSet.add(num);}for (Integer s : hashSet) {if (!hashSet.contains(s - 1)) {length 1;while (hashSet.contains(s)) {length;}maxLength Math.max(length, maxLength);}}return maxLength;}