# 0480. Sliding Window Median

https://leetcode.com/problems/sliding-window-median

## Description

The **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 values.

* For examples, if `arr = [2,3,4]`, the median is `3`.
* For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`.

You are given an integer array `nums` and an integer `k`. 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.

Return _the median array for each window in the original array_. Answers within `10-5` of the actual value will be accepted.

**Example 1:**

```
**Input:** nums = [1,3,-1,-3,5,3,6,7], k = 3
**Output:** [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]
**Explanation:** 
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
```

**Example 2:**

```
**Input:** nums = [1,2,3,4,2,3,1,4,2], k = 3
**Output:** [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]
```

**Constraints:**

* `1 <= k <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`

## ac

```java
class Solution {
    public double[] medianSlidingWindow(int[] nums, int k) {
        // edge cases
        if (nums.length < k) return new double[0];

        // 2 treeset, Integer.compare() avoid overflow
        Comparator<Integer> comp = (a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : a - b;
        TreeSet<Integer> left  = new TreeSet<>(comp);
        TreeSet<Integer> right = new TreeSet<>(comp);

        // sliding window
        double[] res = new double[nums.length - k + 1];
        int l = 0;
        for (int r = 0; r < nums.length; r++) {
            right.add(r);
            left.add(right.pollFirst()); // important, make sure elements in left < right
            // balance(left, right);
            while (left.size() > right.size()) {
                right.add(left.pollLast());
            }

            // window formed
            if (r - l + 1 == k) {
                double median = k % 2 == 0 ? 
                    ((double) nums[left.last()] + (double) nums[right.first()]) / 2.0 
                    : nums[right.first()];
                res[l] = median;

                // move left forward
                if (!left.remove(l)) right.remove(l);
                l++;
            }
        }

        return res;
    }

}

/*
2 treeset
iterate inspect window
similar with https://leetcode.com/problems/find-median-from-data-stream/description/
*/
```
