The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
For examples, if arr = [2,3,4], the median is 3.
For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.
You are given an integer array nums and an integer k. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
Explanation:
| Window position | Median |
|---|---|
| [1 3 -1] -3 5 3 6 7 | 1 |
| 1 [3 -1 -3] 5 3 6 7 | -1 |
| 1 3 [-1 -3 5] 3 6 7 | -1 |
| 1 3 -1 [-3 5 3] 6 7 | 3 |
| 1 3 -1 -3 [5 3 6] 7 | 5 |
| 1 3 -1 -3 5 [3 6 7] | 6 |
Example 2:
Input: nums = [1,2,3,4,2,3,1,4,2], k = 3
Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
Constraints:
- 1 <= k <= nums.length <= 105
- -231 <= nums[i] <= 231 - 1
用一个 max heap(left)来保存当前 window 的左半部分, 用一个 min heap(right)来保存当前 window 的右半部分, 当需要从 heap 中移除 num 的时候我们并真正移除, 而是记录起来, 当这些记录的数字移动到 heap 的 top 的时候我们再将其移除。push 的过程简单来说就是,如果<= top(left), 就 left.push(num), 否则 right.push(num), 如果 push 和 pop 在同一侧, 则不做特殊处理, 如果 push 在 left, pop 在 right, 则需要将 left 的最大值移动到 right, 如果 push 在 right,pop 在 left, 则需要将 right 的最小值移动到 left。因为 left 和 right 分别是 max heap 和 min heap, 所以这两种移动的时间复杂度都是 O(logn)。最后, 如果 k 是奇数则 top(right)是中位数, 如果 k 是偶数则(top(left) + top(right)) / 2 是中位数
use std::cmp::Reverse;
use std::collections::{
BinaryHeap, HashMap};
impl Solution {
pub fn median_sliding_window(nums: Vec<i32>, k: i32) -> Vec<f64> {
if k == 1 {
return nums.into_iter().map(|v| v as f64).collect()

本文介绍了如何解决LeetCode上的滑动窗口中位数问题,通过使用最大堆和最小堆来高效地求解每个窗口的中位数。在窗口移动时,按特定策略更新堆以保持正确性,最终根据窗口大小的奇偶性确定中位数的计算方式。
最低0.47元/天 解锁文章
8万+

被折叠的 条评论
为什么被折叠?



