Leetcode295 Find Median from Data Stream
题目描述
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
1 | [2,3,4]`, the median is `3 |
Design a data structure that supports the following two operations:
- void addNum(int num) - Add a integer number from the data stream to the data structure.
- double findMedian() - Return the median of all elements so far.
Example:
1 | addNum(1) |
思路
两个priority queue,一个queue存较大部分一个queue寸较小部分
较小部分:small = new PriorityQueue
较大部分:large = new PriorityQueue
加入元素:如果large部分为空或者num数大于large的最小元素,则将num加入到large中,反之加入small中。加入后,比较large和small的大小,两个队列的size差不能超多1
计算中位数:如果small和large的大小相同,则取small的最大和large的最小值相加除以2.0;如果small的数量多,则取small数组的最大的那个。
代码
1 | class MedianFinder { |