1g做网站空间,自媒体平台是什么意思,如何优化企业网站,wordpress 关联微信leetcode链接 给定一个未排序的整数数组 nums #xff0c;找出数字连续的最长序列#xff08;不要求序列元素在原数组中连续#xff09;的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1#xff1a;输入#xff1a;nums [100,4,200,1,3,2]
输出找出数字连续的最长序列不要求序列元素在原数组中连续的长度。
请你设计并实现时间复杂度为 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 10^5
-10^9 nums[i] 10^9thought: 这题可先排序然后采用双指针法。其中两个相同的值跳过来实现正确的计数。【应当采用linkedHashSet特点来去重更好使用就不用对重复的进行跳过】‘’’ java
class Solution {public int longestConsecutive(int[] nums) {Arrays.sort(nums);if (nums.length 0) return 0;int len 1,max 1;for (int i 0,ji1;jnums.length;){if (nums[i]1 nums[j]){len;}else if (nums[i] nums[j]){i;j;continue;}else {len 1;}i;j;max maxlen?len:max;}return max;}
}上述方法由于Array.sort的时间复杂度是nlogn。因此看了其他方法采用set去重然后利用连续的特性去获取长度。如下
class Solution {public int longestConsecutive(int[] nums) {int res 0; // 记录最长连续序列的长度SetInteger numSet new HashSet(); // 记录所有的数值for(int num: nums){numSet.add(num); // 将数组中的值加入哈希表中}int seqLen; // 连续序列的长度for(int num: numSet){// 如果当前的数是一个连续序列的起点统计这个连续序列的长度if(!numSet.contains(num - 1)){seqLen 1;while(numSet.contains(num))seqLen; // 不断查找连续序列直到num的下一个数不存在于数组中res Math.max(res, seqLen); // 更新最长连续序列长度}}return res;}
}作者画图小匠
链接https://leetcode.cn/problems/longest-consecutive-sequence/solutions/2362995/javapython3cha-xi-biao-ding-wei-mei-ge-l-xk4c/
来源力扣LeetCode‘’’ python 使用set然后利用连续特性去计算长度。
class Solution:def longestConsecutive(self, nums: List[int]) - int:num_set set(nums)res 0for num in num_set:if (num-1) not in num_set:seq_len 1while (num1) in num_set:seq_len 1num 1res max(res,seq_len)return res