480. Sliding Window Median

https://leetcode.com/problems/sliding-window-median/

solution

# 类似于81题数据流的中位数,两个堆,一个大根堆维护中位数以左的,一个小根堆维护中位数以右的元素

from bisect import insort, bisect_left

class Solution:
    def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
        ans = []
        window = sorted(nums[:k])  # 排序
        
        def get_median(window, k):
            return (window[(k - 1) // 2] + window[k // 2]) / 2.0
        
        ans.append(get_median(window, k))
        
        for i in range(k, len(nums)):            
            index = bisect_left(window, nums[i - k])  # 即将移出窗口的元素,其他的仍然排序
            window.pop(index)

            insort(window, nums[i])
            ans.append(get_median(window, k))
        
        return ans

时间复杂度:O(n x k) 空间复杂度:O(n)

follow up

295. Find Median from Data Stream

Last updated