-
Notifications
You must be signed in to change notification settings - Fork 0
/
S63.java
44 lines (40 loc) · 1.2 KB
/
S63.java
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
package S61_67;
import java.util.PriorityQueue;
/**
* 数据流中的中位数
* Created by Elvis on 2020/1/4.
*/
public class S63 {
public static void main(String[] args) {
Insert(1);
System.out.println(GetMedian());
Insert(5);
System.out.println(GetMedian());
Insert(8);
System.out.println(GetMedian());
Insert(4);
System.out.println(GetMedian());
Insert(3);
System.out.println(GetMedian());
Insert(9);
System.out.println(GetMedian());
Insert(13);
System.out.println(GetMedian());
}
static PriorityQueue<Integer> lHeap = new PriorityQueue<>((a, b) -> b - a); //大根堆
static PriorityQueue<Integer> sHeap = new PriorityQueue<>(); //小根堆
static void Insert(int num) {
lHeap.add(num);
sHeap.add(lHeap.remove());
if (sHeap.size() > lHeap.size()) {
lHeap.add(sHeap.remove());
}
}
static Double GetMedian() {
if (sHeap.size() == lHeap.size()) {
return (sHeap.peek() + lHeap.peek()) / 2.0;
} else {
return (double) lHeap.peek();
}
}
}