LeetCode每日一题(480. Sliding Window Median)

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(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值