LeetCode 128 最长连续序列
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-consecutive-sequence/description/
博主Github:https://github.com/GDUT-Rp/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 <= 1 0 5 10^5 105
- − 1 0 9 -10^9 −109 <= nums[i] <= 1 0 9 10^9 109
解题思路:
方法一:放到map里,只对第一个开始连续的值进行遍历
首先把值都放到map里,然后对每个值都进行循环判断进行有多少连续的,但这样子时间复杂度就不合适了。
因此我们需要跳过那些重复没有必要的遍历,避免【1、2、3、4、5】进入5次。
那么怎么判断是否跳过呢?由于我们要枚举的数 x x x 一定是在数组中不存在前驱数 x − 1 x−1 x−1 的,不然按照上面的分析我们会从 x − 1 x−1 x−1 开始尝试匹配,因此我们每次在哈希表中检查是否存在 x − 1 x−1 x−1 即能判断是否需要跳过了。
Golang
func longestConsecutive(nums []int) int {
numSet := make(map[int]bool)
for _, num := range nums {
numSet[num] = true
}
var ans int
for _, num := range nums {
// 前面没有已经连续的
if _, ok := numSet[num-1]; ok {
continue
}
currentNum := num
currentCount := 1
for numSet[currentNum+1] {
// 有连续就累加
currentNum ++
currentCount ++
}
ans = max(ans, currentCount)
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
ans = 0
for num in num_set:
if num - 1 in num_set:
continue
# 非连续的
current_num = num
current_count = 1
while current_num+1 in num_set:
current_num += 1
current_count += 1
ans = max(ans, current_count)
return ans
复杂度分析
时间复杂度: O ( n ) O(n) O(n),其中 n n n 为数组的长度。
空间复杂度:
O
(
n
)
O(n)
O(n)。哈希表存储数组中所有的数需要
O
(
n
)
O(n)
O(n) 的空间。