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.
Copy 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
Therefore, return the median sliding window as[1,-1,-1,3,5,6]
.
Note:
You may assumek
is always valid, ie:k
is always smaller than input array's size for non-empty array.
2. Implementation
(1) Heap
思路:
Copy class Solution {
public double [] medianSlidingWindow ( int [] nums , int k) {
if (nums == null || nums . length == 0 || k <= 0 ) {
return new double [ 0 ];
}
TreeSet < Node > lowHeap = new TreeSet <>();
TreeSet < Node > highHeap = new TreeSet <>();
int n = nums . length ;
double [] res = new double [n - k + 1 ];
int size = (k + 1 ) / 2 ;
for ( int i = 0 ; i < n; i ++ ) {
add(lowHeap , highHeap , size , new Node(i , ( double )nums[i])) ;
if (i - k + 1 >= 0 ) {
res[i - k + 1 ] = getMedian(lowHeap , highHeap) ;
remove(lowHeap , highHeap , new Node(i - k + 1 , ( double )nums[i - k + 1 ])) ;
}
}
return res;
}
public void add ( TreeSet < Node > lowHeap , TreeSet < Node > highHeap , int size , Node node) {
if ( lowHeap . size () < size) {
lowHeap . add (node);
}
else {
highHeap . add (node);
}
if ( lowHeap . size () == size) {
if ( highHeap . size () > 0 && lowHeap . last () . val > highHeap . first () . val ) {
Node node1 = lowHeap . last ();
Node node2 = highHeap . first ();
lowHeap . remove (node1);
highHeap . remove (node2);
lowHeap . add (node2);
highHeap . add (node1);
}
}
}
public void remove ( TreeSet < Node > lowHeap , TreeSet < Node > highHeap , Node node) {
if ( lowHeap . contains (node)) {
lowHeap . remove (node);
}
else {
highHeap . remove (node);
}
}
public double getMedian ( TreeSet < Node > lowHeap , TreeSet < Node > highHeap) {
return lowHeap . size () == highHeap . size () ? 0.5 * lowHeap . last () . val + 0.5 * highHeap . first () . val : lowHeap . last () . val ;
}
class Node implements Comparable < Node > {
int index;
double val;
public Node ( int index , double val) {
this . index = index;
this . val = val;
}
public int compareTo ( Node that) {
return this . val == that . val ? this . index - that . index : ( int )( this . val - that . val );
}
}
}
3. Time & Space Complexity
Heap: 时间复杂度O(nlogk), 空间复杂度O(n-k) + O(k) => O(n)