Skip to content

Commit c07c7f8

Browse files
committed
剑指Offer,数据流中的中位数
1 parent 4155fa2 commit c07c7f8

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)