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
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 median2
;
then the window move one step forward.
[1, | 2,7,8 | ,5]
, return the median7
;
then the window move one step forward again.
[1,2, | 7,8,5 | ]
, return the median7
;
Solution
仍然可以用min heap, max heap来做。
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) {
// write your code here
List<Integer> result = new ArrayList<Integer>();
if (nums == null || nums.length == 0 || k <= 0 || k > nums.length) {
return result;
}
PriorityQueue<Integer> min = new PriorityQueue<Integer>();
PriorityQueue<Integer> max = new PriorityQueue<Integer>();
int medium = nums[0];
if (k == 1) {
result.add(medium);
}
for (int i = 1; i < nums.length; i++) {
int cur = nums[i];
if (cur >= medium) {
max.offer(cur);
} else {
min.offer(-cur);
}
medium = adjust(min, max, medium);
if (i >= k) {
int delete = nums[i - k];
if (!min.remove(-delete)) {
if (!max.remove(delete)) {
medium = min.size() <= max.size() ? max.poll() : -min.poll();
}
}
}
medium = adjust(min, max, medium);
if (i >= k - 1) {
result.add(medium);
}
}
return result;
}
private int adjust(PriorityQueue<Integer> min, PriorityQueue<Integer> max, int medium) {
if (min.size() + 2 == max.size()) {
min.offer(-medium);
return max.poll();
} else if (min.size() == max.size() + 1) {
max.offer(medium);
return -min.poll();
}
return medium;
}
}