leetcode链接
给定一个未排序的整数数组 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 <= 10^5
-10^9 <= nums[i] <= 10^9
thought: 这题可先排序,然后采用双指针法。其中,两个相同的值跳过来实现正确的计数。【应当采用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,j=i+1;j<nums.length;){
if (nums[i]+1 == nums[j]){
len++;
}else if (nums[i] == nums[j]){
i++;
j++;
continue;
}else {
len = 1;
}
i++;
j++;
max = max<len?len:max;
}
return max;
}
}
上述方法,由于Array.sort的时间复杂度是nlogn。因此看了其他方法,采用set去重,然后利用连续的特性去获取长度。如下:
class Solution {
public int longestConsecutive(int[] nums) {
int res = 0; // 记录最长连续序列的长度
Set<Integer> 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 = 0
for num in num_set:
if (num-1) not in num_set:
seq_len = 1
while (num+1) in num_set:
seq_len += 1
num += 1
res = max(res,seq_len)
return res