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 value.
Examples:
[2,3,4]
, the median is 3
[2,3]
, the median is (2 + 3) / 2 = 2.5
Given an array nums, 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. Your job is to output the median array for each window in the original array.
For example,
Given nums = [1,3,-1,-3,5,3,6,7]
, and k = 3.
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
Therefore, return the median sliding window as [1,-1,-1,3,5,6]
.
思路:跟 Find Median from Data Stream类似,用maxheap minheap去维持中位数,不同的地方就是window移动的时候,需要把头部的元素给去掉,注意后面一定要再balance一下;注意balance的时候,minheap.size() < maxheap.size() - 1,不能忍;
错误点:有负数的的maxheap,不能用(a , b) ->(b - a),一定要用Collections.reverseOrder();
double[] res的size,是n - k + 1;
因为PQ是存的int,那么出来的时候,需要转换成double,然后求median;
class Solution {
PriorityQueue<Integer> minheap ;
PriorityQueue<Integer> maxheap ;
public double[] medianSlidingWindow(int[] nums, int k) {
minheap = new PriorityQueue<>();
maxheap = new PriorityQueue<>(Collections.reverseOrder()); // 这个很重要,reverse order;
int n = nums.length;
double[] res = new double[n - k + 1];
int index = 0;
for(int i = 0; i < nums.length; i++) {
if(maxheap.isEmpty() || nums[i] < maxheap.peek()) {
maxheap.offer(nums[i]);
} else {
minheap.offer(nums[i]);
}
balance();
if(i == k - 1) {
res[index++] = getMedian();
}else if (i >= k) {
remove(nums[i - k]);
balance();
res[index++] = getMedian();
}
}
return res;
}
private void remove(int num) {
if(num <= maxheap.peek()) {
maxheap.remove(num);
} else {
minheap.remove(num);
}
}
private double getMedian() {
if(maxheap.size() == minheap.size() + 1) {
return (double)maxheap.peek();
} else {
return 0.5 * ((double)maxheap.peek() + (double)minheap.peek());
}
}
private void balance() {
while(maxheap.size() < minheap.size()) {
maxheap.add(minheap.poll());
}
while(maxheap.size() > minheap.size() + 1) {
minheap.add(maxheap.poll());
}
}
}