首页 > 学院 > 开发设计 > 正文

295. Find Median from Data Stream

2019-11-06 07:47:26
字体:
来源:转载
供稿:网友

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: [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

public class MedianFinder { PRivate PriorityQueue<Integer> small = new PriorityQueue<Integer>(1000, Collections.reverSEOrder()); private PriorityQueue<Integer> large = new PriorityQueue<Integer>(); // Adds a number into the data structure. public void addNum(int num) { small.offer(num); large.offer(small.poll()); if(small.size() < large.size()) small.offer(large.poll()); } // Returns the median of current data stream public double findMedian() { if(small.size() == large.size()) return (small.peek() + large.peek()) / 2.0; return (double)small.peek(); }};// Your MedianFinder object will be instantiated and called as such:// MedianFinder mf = new MedianFinder();// mf.addNum(1);// mf.findMedian();
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表