https://leetcode.com/problems/sliding-window-median/#/description
给一个数组和滑动窗口,找当前窗口中的中位数
PriorityQueue中的remove是O(k)时间复杂度
类似于给一个数据流,找最近k个数的中位数
public class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
PriorityQueue<Integer> min = new PriorityQueue();
PriorityQueue<Integer> max = new PriorityQueue(new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return i2.compareTo(i1);
}
});
double[] res = new double[nums.length - k + 1];
for (int i = 0; i < k; i++) {
min.offer(nums[i]);
if (min.size() > k / 2) {
max.add(min.poll());
}
}
res[0] = k % 2 == 0 ? ((long) min.peek() + (long) max.peek()) / 2.0 : (double) max.peek();
for (int i = k; i < nums.length; i++) {
if (max.peek() > nums[i]) {
max.add(nums[i]);
if (nums[i - k] <= max.peek()) {
max.remove(nums[i - k]);
} else {
min.remove(nums[i - k]);
min.add(max.poll());
}
} else {
min.add(nums[i]);
if (nums[i - k] <= max.peek()) {
max.remove(nums[i - k]);
max.add(min.poll());
} else {
min.remove(nums[i - k]);
}
}
res[i - k + 1] = k % 2 == 0 ? ((long) min.peek() + (long) max.peek()) / 2.0 : (double) max.peek();
}
return res;
}
}