mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 07:33:45 +00:00
Update 41.1 数据流中的中位数.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+33
-25
@@ -2,7 +2,7 @@
|
||||
|
||||
## 题目链接
|
||||
|
||||
[牛客网](https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?tpId=13&tqId=11216&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
||||
[Leetcode](https://leetcode.cn/problems/shu-ju-liu-zhong-de-zhong-wei-shu-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
@@ -11,32 +11,40 @@
|
||||
## 解题思路
|
||||
|
||||
```java
|
||||
/* 大顶堆,存储左半边元素 */
|
||||
private PriorityQueue<Integer> left = new PriorityQueue<>((o1, o2) -> o2 - o1);
|
||||
/* 小顶堆,存储右半边元素,并且右半边元素都大于左半边 */
|
||||
private PriorityQueue<Integer> right = new PriorityQueue<>();
|
||||
/* 当前数据流读入的元素个数 */
|
||||
private int N = 0;
|
||||
class MedianFinder {
|
||||
|
||||
/* 大顶堆,存储左半边元素 */
|
||||
private PriorityQueue<Integer> left = new PriorityQueue<>((o1, o2) -> o2 - o1);
|
||||
/* 小顶堆,存储右半边元素,并且右半边元素都大于左半边 */
|
||||
private PriorityQueue<Integer> right = new PriorityQueue<>();
|
||||
/* 当前数据流读入的元素个数 */
|
||||
private int N = 0;
|
||||
|
||||
public MedianFinder() {
|
||||
|
||||
public void Insert(Integer val) {
|
||||
/* 插入要保证两个堆存于平衡状态 */
|
||||
if (N % 2 == 0) {
|
||||
/* N 为偶数的情况下插入到右半边。
|
||||
* 因为右半边元素都要大于左半边,但是新插入的元素不一定比左半边元素来的大,
|
||||
* 因此需要先将元素插入左半边,然后利用左半边为大顶堆的特点,取出堆顶元素即为最大元素,此时插入右半边 */
|
||||
left.add(val);
|
||||
right.add(left.poll());
|
||||
} else {
|
||||
right.add(val);
|
||||
left.add(right.poll());
|
||||
}
|
||||
N++;
|
||||
}
|
||||
|
||||
public Double GetMedian() {
|
||||
if (N % 2 == 0)
|
||||
return (left.peek() + right.peek()) / 2.0;
|
||||
else
|
||||
return (double) right.peek();
|
||||
public void addNum(int num) {
|
||||
/* 插入要保证两个堆存于平衡状态 */
|
||||
if (N % 2 == 0) {
|
||||
/* N 为偶数的情况下插入到右半边。
|
||||
* 因为右半边元素都要大于左半边,但是新插入的元素不一定比左半边元素来的大,
|
||||
* 因此需要先将元素插入左半边,然后利用左半边为大顶堆的特点,取出堆顶元素即为最大元素,此时插入右半边 */
|
||||
left.add(num);
|
||||
right.add(left.poll());
|
||||
} else {
|
||||
right.add(num);
|
||||
left.add(right.poll());
|
||||
}
|
||||
N++;
|
||||
}
|
||||
|
||||
public double findMedian() {
|
||||
if (N % 2 == 0) {
|
||||
return (left.peek() + right.peek()) / 2.0;
|
||||
} else {
|
||||
return (double) right.peek();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user