> For the complete documentation index, see [llms.txt](https://liuyang89116.gitbook.io/my-leetcode-book/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://liuyang89116.gitbook.io/my-leetcode-book/chapter_7_data_structure/heap/problem-295-find-median-from-data-stream.md).

# Problem 295: Find Median from Data Stream

> <https://leetcode.com/problems/find-median-from-data-stream/>

## 思路

* 这道题十分巧妙。要想得到中位数，那么我们可以把一串数从中间一劈为二，如果左右的个数相同，那么左边右边加起来除以二；如果不相等，那么取右边的（因为默认右边多）
* 左边最大堆，右边最小堆。维持最大堆的时候，add 一个负数就可以了。

```java
public class MedianFinder {

    Queue<Integer> left = new PriorityQueue<Integer>();
    Queue<Integer> right = new PriorityQueue<Integer>();

    // Adds a number into the data structure.
    public void addNum(int num) {
        right.offer(num);
        left.offer(-right.poll());
        if (left.size() > right.size()) {
            right.add(-left.poll());
        }
    }

    // Returns the median of current data stream
    public double findMedian() {
        if (right.size() > left.size()) {
            return (double) right.peek();
        } else {
            return (double) (right.peek() - left.peek()) / 2;
        }
    }
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();
```

## 易错点

1. Queue 的操作 &#x20;

   **offer() / poll()** &#x20;

   联想 Stack 的操作： &#x20;

   push() / pop() &#x20;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://liuyang89116.gitbook.io/my-leetcode-book/chapter_7_data_structure/heap/problem-295-find-median-from-data-stream.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
