480 Sliding Window Median

1. Question

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 is3
[2,3], the median is(2 + 3) / 2 = 2.5
Given an arraynums, there is a sliding window of sizekwhich is moving from the very left of the array to the very right. You can only see theknumbers 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, Givennums=[1,3,-1,-3,5,3,6,7], andk= 3.
1
Window position Median
2
--------------- -----
3
[1 3 -1] -3 5 3 6 7 1
4
1 [3 -1 -3] 5 3 6 7 -1
5
1 3 [-1 -3 5] 3 6 7 -1
6
1 3 -1 [-3 5 3] 6 7 3
7
1 3 -1 -3 [5 3 6] 7 5
8
1 3 -1 -3 5 [3 6 7] 6
Copied!
Therefore, return the median sliding window as[1,-1,-1,3,5,6].
Note: You may assumekis always valid, ie:kis always smaller than input array's size for non-empty array.

2. Implementation

(1) Heap
思路:
1
class Solution {
2
public double[] medianSlidingWindow(int[] nums, int k) {
3
if (nums == null || nums.length == 0 || k <= 0) {
4
return new double[0];
5
}
6
7
TreeSet<Node> lowHeap = new TreeSet<>();
8
TreeSet<Node> highHeap = new TreeSet<>();
9
10
int n = nums.length;
11
double[] res = new double[n - k + 1];
12
int size = (k + 1) / 2;
13
14
for (int i = 0; i < n; i++) {
15
add(lowHeap, highHeap, size, new Node(i, (double)nums[i]));
16
17
if (i - k + 1 >= 0) {
18
res[i - k + 1] = getMedian(lowHeap, highHeap);
19
remove(lowHeap, highHeap, new Node(i - k + 1, (double)nums[i - k + 1]));
20
}
21
}
22
return res;
23
}
24
25
public void add(TreeSet<Node> lowHeap, TreeSet<Node> highHeap, int size, Node node) {
26
if (lowHeap.size() < size) {
27
lowHeap.add(node);
28
}
29
else {
30
highHeap.add(node);
31
}
32
33
if (lowHeap.size() == size) {
34
if (highHeap.size() > 0 && lowHeap.last().val > highHeap.first().val) {
35
Node node1 = lowHeap.last();
36
Node node2 = highHeap.first();
37
lowHeap.remove(node1);
38
highHeap.remove(node2);
39
lowHeap.add(node2);
40
highHeap.add(node1);
41
}
42
}
43
}
44
45
public void remove(TreeSet<Node> lowHeap, TreeSet<Node> highHeap, Node node) {
46
if (lowHeap.contains(node)) {
47
lowHeap.remove(node);
48
}
49
else {
50
highHeap.remove(node);
51
}
52
}
53
54
public double getMedian(TreeSet<Node> lowHeap, TreeSet<Node> highHeap) {
55
return lowHeap.size() == highHeap.size() ? 0.5 * lowHeap.last().val + 0.5 * highHeap.first().val : lowHeap.last().val;
56
}
57
58
class Node implements Comparable<Node> {
59
int index;
60
double val;
61
62
public Node (int index, double val) {
63
this.index = index;
64
this.val = val;
65
}
66
67
public int compareTo(Node that) {
68
return this.val == that.val ? this.index - that.index : (int)(this.val - that.val);
69
}
70
}
71
}
Copied!

3. Time & Space Complexity

Heap: 时间复杂度O(nlogk), 空间复杂度O(n-k) + O(k) => O(n)