forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode 480.java
More file actions
46 lines (37 loc) · 1.48 KB
/
Leetcode 480.java
File metadata and controls
46 lines (37 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
Sliding Window Median
https://leetcode.com/problems/sliding-window-median/
*/
class Solution {
PriorityQueue<Integer> maxHeap=new PriorityQueue<>(Collections.reverseOrder());
PriorityQueue<Integer> minHeap=new PriorityQueue<>();
public double[] medianSlidingWindow(int[] nums, int k) {
int i=0,j=0;
double[] ans=new double[nums.length-k+1];
while(j<nums.length){
if(maxHeap.isEmpty() || maxHeap.peek()>=nums[j])
maxHeap.offer(nums[j]);
else minHeap.offer(nums[j]);
if(maxHeap.size()>minHeap.size()+1)
minHeap.offer(maxHeap.poll());
else if(maxHeap.size()<minHeap.size())
maxHeap.offer(minHeap.poll());
if(j-i+1<k) j++;
else if(j-i+1==k){
if(maxHeap.size()==minHeap.size())
ans[i]=maxHeap.peek()/2.0+minHeap.peek()/2.0;
else ans[i]=maxHeap.peek();
// remove ith element
if(nums[i]<=maxHeap.peek())
maxHeap.remove(nums[i]);
else minHeap.remove(nums[i]);
if(maxHeap.size()>minHeap.size()+1)
minHeap.offer(maxHeap.poll());
else if(maxHeap.size()<minHeap.size())
maxHeap.offer(minHeap.poll());
i++;j++;
}
}
return ans;
}
}