We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 4155fa2 commit c07c7f8Copy full SHA for c07c7f8
1 file changed
swordoffer/MedianNumberSolution.java
@@ -0,0 +1,29 @@
1
+import java.util.Collections;
2
+import java.util.PriorityQueue;
3
+
4
+/**
5
+ * 剑指Offer,数据流中的中位数
6
+ */
7
8
+public class MedianNumberSolution {
9
10
+ PriorityQueue<Integer> min = new PriorityQueue<>();
11
+ PriorityQueue<Integer> max = new PriorityQueue<>(Collections.reverseOrder());
12
13
+ public void Insert(Integer num) {
14
+ max.offer(num);
15
+ min.offer(max.poll());
16
+ if (max.size() < min.size()) {
17
+ max.offer(min.poll());
18
+ }
19
20
21
+ public Double GetMedian() {
22
+ if (max.size() == min.size()) {
23
+ return (max.peek() + min.peek() ) / 2.0;
24
25
+ return (double)max.peek();
26
27
28
29
+}
0 commit comments