File tree 2 files changed +15
-14
lines changed
solution/295.Find Median from Data Stream
2 files changed +15
-14
lines changed Original file line number Diff line number Diff line change 5
5
6
6
例如,
7
7
8
- [ 2,3,4] 的中位数是 3
8
+ ` [2,3,4] ` 的中位数是 ` 3 `
9
9
10
- [ 2,3] 的中位数是 (2 + 3) / 2 = 2.5
10
+ ` [2,3] ` 的中位数是 ` (2 + 3) / 2 = 2.5 `
11
11
12
12
设计一个支持以下两种操作的数据结构:
13
13
@@ -25,8 +25,8 @@ findMedian() -> 2
25
25
26
26
进阶:
27
27
28
- - 1 . 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
29
- - 2 . 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
28
+ - 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
29
+ - 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
30
30
31
31
### 解法
32
32
维护一个大根堆 bigRoot 和一个小根堆 smallRoot,若有 n 个数,较小的 n/2 个数放在大根堆,而较大的 n/2 个数放在小根堆。
@@ -48,17 +48,17 @@ class MedianFinder {
48
48
49
49
public void addNum (int num ) {
50
50
if (bigRoot. isEmpty() || bigRoot. peek() > num) {
51
- bigRoot. add (num);
51
+ bigRoot. offer (num);
52
52
} else {
53
- smallRoot. add (num);
53
+ smallRoot. offer (num);
54
54
}
55
55
56
56
int size1 = bigRoot. size();
57
57
int size2 = smallRoot. size();
58
58
if (size1 - size2 > 1 ) {
59
- smallRoot. add (bigRoot. poll());
59
+ smallRoot. offer (bigRoot. poll());
60
60
} else if (size2 - size1 > 1 ) {
61
- bigRoot. add (smallRoot. poll());
61
+ bigRoot. offer (smallRoot. poll());
62
62
}
63
63
}
64
64
Original file line number Diff line number Diff line change @@ -11,17 +11,17 @@ public MedianFinder() {
11
11
12
12
public void addNum (int num ) {
13
13
if (bigRoot .isEmpty () || bigRoot .peek () > num ) {
14
- bigRoot .add (num );
14
+ bigRoot .offer (num );
15
15
} else {
16
- smallRoot .add (num );
16
+ smallRoot .offer (num );
17
17
}
18
18
19
19
int size1 = bigRoot .size ();
20
20
int size2 = smallRoot .size ();
21
21
if (size1 - size2 > 1 ) {
22
- smallRoot .add (bigRoot .poll ());
22
+ smallRoot .offer (bigRoot .poll ());
23
23
} else if (size2 - size1 > 1 ) {
24
- bigRoot .add (smallRoot .poll ());
24
+ bigRoot .offer (smallRoot .poll ());
25
25
}
26
26
}
27
27
@@ -36,6 +36,7 @@ public double findMedian() {
36
36
37
37
/**
38
38
* 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();
41
42
*/
You can’t perform that action at this time.
0 commit comments