Sliding Window Median

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 1: Two balanced heap.

public ArrayList<Integer> medianSlidingWindow(int[] nums, int k) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    if(nums == null || nums.length == 0) {
        return res;
    }
    PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
    int median = nums[0];
    for (int i = 0; i < nums.length; i++) {
        if(i != 0) {
            if (nums[i] < median) {
                maxHeap.offer(nums[i]);
            }
            else {
                minHeap.offer(nums[i]);
            }
        }
        if (i >= k) {
            //remove first element so that keep window size to k.
            if(nums[i - k] == median) {
                if(minHeap.size() != 0) {
                    median = minHeap.poll();
                }
                else if(maxHeap.size() != 0) {
                    median = maxHeap.poll();
                }
            }
            else if(nums[i - k] > median) {
                minHeap.remove(nums[i - k]);
            }
            else {
                maxHeap.remove(nums[i - k]);
            }
        }
        if (minHeap.size() < maxHeap.size()) {
            minHeap.offer(median);
            median = maxHeap.poll();
        }
        else if (maxHeap.size() + 1 < minHeap.size()) {
            maxHeap.offer(median);
            median = minHeap.poll();
        }
        if (i >= k - 1) {
            res.add(median);            
        }
    }
    return res;
}

results matching ""

    No results matching ""