LeetCode 题解工作台
统计中位数为 K 的子数组
给你一个长度为 n 的数组 nums ,该数组由从 1 到 n 的 不同 整数组成。另给你一个正整数 k 。 统计并返回 nums 中的 中位数 等于 k 的非空子数组的数目。 注意: 数组的中位数是按 递增 顺序排列后位于 中间 的那个元素,如果数组长度为偶数,则中位数是位于中间靠 左 的那个元素…
3
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数组·哈希·扫描
答案摘要
我们先找到中位数 在数组中的位置 ,然后从 开始向两边遍历,统计中位数为 的子数组的数目。 定义一个答案变量 ,表示中位数为 的子数组的数目。初始时 $ans = 1$,表示当前有一个长度为 的子数组,其中位数为 。另外,定义一个计数器 ,用于统计当前遍历过的数组中,「比 大的元素的个数」与「比 小的元素的个数」的差值的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个长度为 n 的数组 nums ,该数组由从 1 到 n 的 不同 整数组成。另给你一个正整数 k 。
统计并返回 nums 中的 中位数 等于 k 的非空子数组的数目。
注意:
- 数组的中位数是按 递增 顺序排列后位于 中间 的那个元素,如果数组长度为偶数,则中位数是位于中间靠 左 的那个元素。
- 例如,
[2,3,1,4]的中位数是2,[8,4,3,5,1]的中位数是4。
- 例如,
- 子数组是数组中的一个连续部分。
示例 1:
输入:nums = [3,2,1,4,5], k = 4 输出:3 解释:中位数等于 4 的子数组有:[4]、[4,5] 和 [1,4,5] 。
示例 2:
输入:nums = [2,3,1], k = 3 输出:1 解释:[3] 是唯一一个中位数等于 3 的子数组。
提示:
n == nums.length1 <= n <= 1051 <= nums[i], k <= nnums中的整数互不相同
解题思路
方法一:遍历 + 计数
我们先找到中位数 在数组中的位置 ,然后从 开始向两边遍历,统计中位数为 的子数组的数目。
定义一个答案变量 ,表示中位数为 的子数组的数目。初始时 ,表示当前有一个长度为 的子数组,其中位数为 。另外,定义一个计数器 ,用于统计当前遍历过的数组中,「比 大的元素的个数」与「比 小的元素的个数」的差值的个数。
接下来,从 开始向右遍历,我们维护一个变量 ,表示当前右侧子数组中「比 大的元素的个数」与「比 小的元素的个数」的差值。如果 ,则当前右侧子数组的中位数为 ,答案变量 自增 。然后,我们将 的值加入计数器 中。
同理,从 开始向左遍历,同样维护一个变量 ,表示当前左侧子数组中「比 大的元素的个数」与「比 小的元素的个数」的差值。如果 ,则当前左侧子数组的中位数为 ,答案变量 自增 。如果 或 也在计数器中,说明当前存在跨越 左右两侧的子数组,其中位数为 ,答案变量 增加计数器中对应的值,即 。
最后,返回答案变量 即可。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
在编码上,我们可以直接开一个长度为 的数组,用于统计当前数组中,比 大的元素的个数与比 小的元素的个数的差值,每一次我们将差值加上 ,即可将差值的范围从 转换为 。
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
i = nums.index(k)
cnt = Counter()
ans = 1
x = 0
for v in nums[i + 1 :]:
x += 1 if v > k else -1
ans += 0 <= x <= 1
cnt[x] += 1
x = 0
for j in range(i - 1, -1, -1):
x += 1 if nums[j] > k else -1
ans += 0 <= x <= 1
ans += cnt[-x] + cnt[-x + 1]
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate effectively leverages the array transformation to simplify the median problem.
- question_mark
The candidate is comfortable using hash maps to track prefix sums and identify subarrays.
- question_mark
The candidate is able to explain the trade-off between brute force methods and the efficient use of prefix sums and hash lookups.
常见陷阱
外企场景- error
Not recognizing that the problem can be reduced to finding subarrays with a sum of zero.
- error
Misunderstanding the transformation of the array into 1, -1, and 0 values.
- error
Failing to efficiently count subarrays with hash maps, leading to time complexity issues.
进阶变体
外企场景- arrow_right_alt
Consider adding duplicate values in the array and adjusting the approach accordingly.
- arrow_right_alt
Explore the possibility of applying the solution to non-distinct integer arrays.
- arrow_right_alt
Modify the problem to allow for non-zero medians in subarrays, which could require different transformation or counting logic.