LeetCode 题解工作台
数组中紧跟 key 之后出现最频繁的数字
给你一个下标从 0 开始的整数数组 nums ,同时给你一个整数 key ,它在 nums 出现过。 统计 在 nums 数组中紧跟着 key 后面出现的不同整数 target 的出现次数。换言之, target 的出现次数为满足以下条件的 i 的数目: 0 nums[i] == key 且 num…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用一个哈希表或数组 记录每个 出现的次数,用一个变量 维护 出现的最大次数,初始时 $\textit{mx} = 0$。 遍历数组 ,如果 $\textit{nums}[i] = \textit{key}$,则 $\textit{nums}[i + 1]$ 出现的次数 $\textit{cnt}[\textit{nums}[i + 1]]$ 加一,如果此时 $\textit{mx} \…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,同时给你一个整数 key ,它在 nums 出现过。
统计 在 nums 数组中紧跟着 key 后面出现的不同整数 target 的出现次数。换言之,target 的出现次数为满足以下条件的 i 的数目:
0 <= i <= n - 2nums[i] == key且nums[i + 1] == target。
请你返回出现 最多 次数的 target 。测试数据保证出现次数最多的 target 是唯一的。
示例 1:
输入:nums = [1,100,200,1,100], key = 1 输出:100 解释:对于 target = 100 ,在下标 1 和 4 处出现过 2 次,且都紧跟着 key 。 没有其他整数在 key 后面紧跟着出现,所以我们返回 100 。
示例 2:
输入:nums = [2,2,2,2,3], key = 2 输出:2 解释:对于 target = 2 ,在下标 1 ,2 和 3 处出现过 3 次,且都紧跟着 key 。 对于 target = 3 ,在下标 4 出出现过 1 次,且紧跟着 key 。 target = 2 是紧跟着 key 之后出现次数最多的数字,所以我们返回 2 。
提示:
2 <= nums.length <= 10001 <= nums[i] <= 1000- 测试数据保证答案是唯一的。
解题思路
方法一:遍历计数
我们用一个哈希表或数组 记录每个 出现的次数,用一个变量 维护 出现的最大次数,初始时 。
遍历数组 ,如果 ,则 出现的次数 加一,如果此时 ,则更新 ,并更新答案 。
遍历结束后,返回答案 。
时间复杂度 ,空间复杂度 。其中 和 分别为数组 的长度和数组 中元素的最大值。
class Solution:
def mostFrequent(self, nums: List[int], key: int) -> int:
cnt = Counter()
ans = mx = 0
for a, b in pairwise(nums):
if a == key:
cnt[b] += 1
if mx < cnt[b]:
mx = cnt[b]
ans = b
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They mention counting the number of times each target follows key, which points straight to scanning adjacent pairs and updating frequencies.
- question_mark
They emphasize immediate followers, which rules out subsequence logic, window logic, or counting all elements after key.
- question_mark
They guarantee the answer is unique, so the interviewer expects a simple max-frequency selection without tie-breaking branches.
常见陷阱
外企场景- error
Counting every value that appears anywhere after key instead of only the value at index i+1 when nums[i] == key.
- error
Iterating to the last index and reading nums[i+1], which causes an out-of-bounds error on the final element.
- error
Building a full frequency map of nums first, which solves the wrong problem because global counts do not reflect followers of key.
进阶变体
外企场景- arrow_right_alt
Return the top k most frequent values that immediately follow key instead of only the unique best target.
- arrow_right_alt
Handle multiple query keys efficiently by preprocessing follower counts for every value in the array.
- arrow_right_alt
Remove the uniqueness guarantee and define a tie rule such as smallest target or first target to reach the maximum count.