295. Find Median from Data Stream***
2017-02-26 18:36
288 查看
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.
Examples:
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.
For example:
Examples:
[2,3,4], the median is
3
[2,3], the median is
(2 + 3) / 2 = 2.5
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.
For example:
addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2
class MedianFinder { private Queue<Long> small = new PriorityQueue(), large = new PriorityQueue(); public void addNum(int num) { large.add((long) num); small.add(-large.poll()); if (large.size() < small.size()) large.add(-small.poll()); } public double findMedian() { return large.size() > small.size() ? large.peek() : (large.peek() - small.peek()) / 2.0; } };总结:机智哭了,不过可以用binarysearch做,随时插入。两次比较是为了保证新加入的元素和前半部分和后半部分都要比较,而不是一半。
相关文章推荐
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream&数据流中的中位数
- 解题报告:295. Find Median from Data Stream
- 295. Find Median from Data Stream
- leetcode:295. Find Median from Data Stream
- 295. Find Median from Data Stream
- LeetCode Find Median from Data Stream
- Leetcode: Find Median from Data Stream
- 数据结构问题集锦 - Find Median from Data Stream
- 《leetcode》:Find Median from Data Stream
- leetcode:Find Median from Data Stream
- LeetCode295——Find Median from Data Stream
- LeetCode Find Median from Data Stream 堆
- 295. Find Median from Data Stream
- [LeetCode]Find Median from Data Stream
- 295. Find Median from Data Stream