LeetCode 题解工作台
最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。 示例 1: 输入: nums = [100,4,200,1,3,2] 输出: 4 解释: 最长数字连续序列是 [1, 2, 3, 4]。它的…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表 存储数组中所有的元素,用一个变量 记录最长连续序列的长度,用一个哈希表 记录每个元素 所在的连续序列的长度。 接下来,我们遍历数组中每个元素 ,用一个临时变量 记录当前连续序列的最大值,初始时 $y = x$。然后,我们不断尝试匹配 $y+1, y+2, y+3, \dots$,直到匹配不到为止,过程中将匹配到的元素从哈希表 中移除。那么,当前元素 所在的连续序…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定一个未排序的整数数组 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
示例 3:
输入:nums = [1,0,1,2] 输出:3
提示:
0 <= nums.length <= 105-109 <= nums[i] <= 109
解题思路
方法一:哈希表
我们可以用一个哈希表 存储数组中所有的元素,用一个变量 记录最长连续序列的长度,用一个哈希表 记录每个元素 所在的连续序列的长度。
接下来,我们遍历数组中每个元素 ,用一个临时变量 记录当前连续序列的最大值,初始时 。然后,我们不断尝试匹配 ,直到匹配不到为止,过程中将匹配到的元素从哈希表 中移除。那么,当前元素 所在的连续序列的长度即为 ,然后更新答案 。
遍历结束后,返回答案 即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
ans = 0
d = defaultdict(int)
for x in nums:
y = x
while y in s:
s.remove(y)
y += 1
d[x] = d[y] + y - x
ans = max(ans, d[x])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand how to use a hash table for constant-time lookups?
- question_mark
Can you explain why this solution guarantees O(n) time complexity?
- question_mark
Will you consider edge cases such as empty arrays or single-element arrays?
常见陷阱
外企场景- error
Relying on brute force methods like sorting or nested loops leads to suboptimal O(n log n) or O(n^2) time complexity.
- error
Forgetting to handle edge cases, like arrays with one element or empty arrays, can lead to incorrect results.
- error
Not using the hash table efficiently, such as by repeatedly checking for consecutive numbers instead of storing them all for quick lookups.
进阶变体
外企场景- arrow_right_alt
Find the longest consecutive sequence in a sorted array.
- arrow_right_alt
Determine the longest consecutive subsequence in an array of integers with duplicates.
- arrow_right_alt
Implement a solution using Union-Find to track consecutive sequences.