|
| 1 | +use std::cmp::Reverse; |
| 2 | +use std::collections::BinaryHeap; |
| 3 | + |
1 | 4 | struct MedianFinder {
|
2 |
| - nums: Vec<i32>, |
| 5 | + minQ: BinaryHeap<Reverse<i32>>, |
| 6 | + maxQ: BinaryHeap<i32>, |
3 | 7 | }
|
4 | 8 |
|
5 |
| -/** |
6 |
| - * `&self` means the method takes an immutable reference. |
7 |
| - * If you need a mutable reference, change it to `&mut self` instead. |
8 |
| - */ |
9 | 9 | impl MedianFinder {
|
10 |
| - /** initialize your data structure here. */ |
11 | 10 | fn new() -> Self {
|
12 |
| - Self { nums: Vec::new() } |
| 11 | + MedianFinder { |
| 12 | + minQ: BinaryHeap::new(), |
| 13 | + maxQ: BinaryHeap::new(), |
| 14 | + } |
13 | 15 | }
|
14 | 16 |
|
15 | 17 | fn add_num(&mut self, num: i32) {
|
16 |
| - let mut l = 0; |
17 |
| - let mut r = self.nums.len(); |
18 |
| - while l < r { |
19 |
| - let mid = (l + r) >> 1; |
20 |
| - if self.nums[mid] < num { |
21 |
| - l = mid + 1; |
22 |
| - } else { |
23 |
| - r = mid; |
24 |
| - } |
| 18 | + self.maxQ.push(num); |
| 19 | + self.minQ.push(Reverse(self.maxQ.pop().unwrap())); |
| 20 | + |
| 21 | + if self.minQ.len() > self.maxQ.len() + 1 { |
| 22 | + self.maxQ.push(self.minQ.pop().unwrap().0); |
25 | 23 | }
|
26 |
| - self.nums.insert(l, num); |
27 | 24 | }
|
28 | 25 |
|
29 | 26 | fn find_median(&self) -> f64 {
|
30 |
| - let n = self.nums.len(); |
31 |
| - if (n & 1) == 1 { |
32 |
| - return f64::from(self.nums[n >> 1]); |
| 27 | + if self.minQ.len() == self.maxQ.len() { |
| 28 | + let min_top = self.minQ.peek().unwrap().0; |
| 29 | + let max_top = *self.maxQ.peek().unwrap(); |
| 30 | + (min_top + max_top) as f64 / 2.0 |
| 31 | + } else { |
| 32 | + self.minQ.peek().unwrap().0 as f64 |
33 | 33 | }
|
34 |
| - f64::from(self.nums[n >> 1] + self.nums[(n >> 1) - 1]) / 2.0 |
35 | 34 | }
|
36 | 35 | }
|
0 commit comments