Skip to content

Commit c816f77

Browse files
committed
Update solution 295
1 parent 7f77ebd commit c816f77

File tree

2 files changed

+15
-14
lines changed

2 files changed

+15
-14
lines changed

solution/295.Find Median from Data Stream/README.md

+8-8
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55

66
例如,
77

8-
[2,3,4] 的中位数是 3
8+
`[2,3,4]` 的中位数是 `3`
99

10-
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
10+
`[2,3]` 的中位数是 `(2 + 3) / 2 = 2.5`
1111

1212
设计一个支持以下两种操作的数据结构:
1313

@@ -25,8 +25,8 @@ findMedian() -> 2
2525

2626
进阶:
2727

28-
- 1. 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
29-
- 2. 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
28+
- 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
29+
- 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
3030

3131
### 解法
3232
维护一个大根堆 bigRoot 和一个小根堆 smallRoot,若有 n 个数,较小的 n/2 个数放在大根堆,而较大的 n/2 个数放在小根堆。
@@ -48,17 +48,17 @@ class MedianFinder {
4848

4949
public void addNum(int num) {
5050
if (bigRoot.isEmpty() || bigRoot.peek() > num) {
51-
bigRoot.add(num);
51+
bigRoot.offer(num);
5252
} else {
53-
smallRoot.add(num);
53+
smallRoot.offer(num);
5454
}
5555

5656
int size1 = bigRoot.size();
5757
int size2 = smallRoot.size();
5858
if (size1 - size2 > 1) {
59-
smallRoot.add(bigRoot.poll());
59+
smallRoot.offer(bigRoot.poll());
6060
} else if (size2 - size1 > 1) {
61-
bigRoot.add(smallRoot.poll());
61+
bigRoot.offer(smallRoot.poll());
6262
}
6363
}
6464

solution/295.Find Median from Data Stream/Solution.java

+7-6
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,17 @@ public MedianFinder() {
1111

1212
public void addNum(int num) {
1313
if (bigRoot.isEmpty() || bigRoot.peek() > num) {
14-
bigRoot.add(num);
14+
bigRoot.offer(num);
1515
} else {
16-
smallRoot.add(num);
16+
smallRoot.offer(num);
1717
}
1818

1919
int size1 = bigRoot.size();
2020
int size2 = smallRoot.size();
2121
if (size1 - size2 > 1) {
22-
smallRoot.add(bigRoot.poll());
22+
smallRoot.offer(bigRoot.poll());
2323
} else if (size2 - size1 > 1) {
24-
bigRoot.add(smallRoot.poll());
24+
bigRoot.offer(smallRoot.poll());
2525
}
2626
}
2727

@@ -36,6 +36,7 @@ public double findMedian() {
3636

3737
/**
3838
* Your MedianFinder object will be instantiated and called as such:
39-
* MedianFinder obj = new MedianFinder(); obj.addNum(num); double param_2 =
40-
* obj.findMedian();
39+
* MedianFinder obj = new MedianFinder();
40+
* obj.addNum(num);
41+
* double param_2 = obj.findMedian();
4142
*/

0 commit comments

Comments
 (0)