Description
Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array, find the median of the element inside the window at each moving. (If there are even numbers in the array, return the N/2-th number after sorting the element in the window. )
Example
Example 1:
Input:
[1,2,7,8,5]
3
Output:
[2,7,7]
Explanation:
At first the window is at the start of the array like this `[ | 1,2,7 | ,8,5]` , return the median `2`;
then the window move one step forward.`[1, | 2,7,8 | ,5]`, return the median `7`;
then the window move one step forward again.`[1,2, | 7,8,5 | ]`, return the median `7`;
Example 2:
Input:
[1,2,3,4,5,6,7]
4
Output:
[2,3,4,5]
Explanation:
At first the window is at the start of the array like this `[ | 1,2,3,4, | 5,6,7]` , return the median `2`;
then the window move one step forward.`[1,| 2,3,4,5 | 6,7]`, return the median `3`;
then the window move one step forward again.`[1,2, | 3,4,5,6 | 7 ]`, return the median `4`;
then the window move one step forward again.`[1,2,3,| 4,5,6,7 ]`, return the median `5`;
Challenge
O(nlog(n)) time
思路:使用两个PriorityQueue, 依次遍历元素,当元素小于最大堆堆顶或最大堆为空则放入最大堆,否则放入最小堆。同时 保证maxHeap的size比minHeap多一个或相等,median即为最大堆的堆叠元素。
public class Solution { /** * @param nums: A list of integers * @param k: An integer * @return: The median of the element inside the window at each moving */ private PriorityQueue<Integer> maxHeap, minHeap; public List<Integer> medianSlidingWindow(int[] nums, int k) { List<Integer> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } int n = nums.length; maxHeap = new PriorityQueue<Integer>(n, Collections.reverseOrder()); minHeap = new PriorityQueue<Integer>(n); for (int i = 0; i < n; i++) { if (i - k >= 0) { if (nums[i - k] > maxHeap.peek()) { minHeap.remove(nums[i - k]); } else { maxHeap.remove(nums[i - k]); } balance(); } if (maxHeap.size() == 0 || nums[i] < maxHeap.peek()) { maxHeap.offer(nums[i]); } else { minHeap.offer(nums[i]); } balance(); if (i - k >= -1) { res.add(maxHeap.peek()); } } return res; } private void balance() { // 保证maxHeap的size比minHeap多一个或相等 while (maxHeap.size() < minHeap.size()) { maxHeap.offer(minHeap.poll()); } while (minHeap.size() < maxHeap.size() - 1) { minHeap.offer(maxHeap.poll()); } } }