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
For array [1,2,7,8,5]
, moving window size k = 3. return [2,7,7]
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
;
双堆
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
*/
public List<Integer> medianSlidingWindow(int[] nums, int k) {
List<Integer> res = new ArrayList<Integer>();
if(nums==null || nums.length==0 || k==0)
return res;
int n = nums.length;
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>();
//init
for(int i=0; i<n; i++){
//入堆
//调整堆尺寸,保证大顶堆个数<=小顶堆
//维持长为k的window内的元素的堆
if(minHeap.size()==0) {
minHeap.add(nums[i]);
}else {
if(nums[i]<=minHeap.peek()){
minHeap.add(nums[i]);
if(minHeap.size()>maxHeap.size()+1)//调整目前堆的平衡
maxHeap.add(minHeap.poll());
}else{
maxHeap.add(nums[i]);
if(minHeap.size()<maxHeap.size())
minHeap.add(maxHeap.poll());//调整目前堆的平衡
}
}
//输出当前窗口(两个堆)的中位数
if(minHeap.size()+maxHeap.size()==k){
res.add(minHeap.peek());
//向右移动窗口一格
//即删除窗口的第一格
//index = i-k+1
if(nums[i-k+1]<=res.get(res.size()-1)){//在小堆中
minHeap.remove(nums[i-k+1]);
if(minHeap.size()<maxHeap.size())
minHeap.add(maxHeap.poll());//调整目前堆的平衡
}else{
maxHeap.remove(nums[i-k+1]);
if(minHeap.size()>maxHeap.size()+1)//调整目前堆的平衡
maxHeap.add(minHeap.poll());
}
}
}
return res;
}
}