classMedianFinder{ public PriorityQueue<Integer> minheap, maxheap; publicMedianFinder(){ //维护较大的元素的最小堆 maxheap = new PriorityQueue<Integer>(Collections.reverseOrder()); //维护较小元素的最大堆 minheap = new PriorityQueue<Integer>(); }
// Adds a number into the data structure. publicvoidaddNum(int num){ maxheap.add(num); minheap.add(maxheap.poll()); if (maxheap.size() < minheap.size()) { maxheap.add(minheap.poll()); } }
// Returns the median of current data stream publicdoublefindMedian(){ if (maxheap.size() == minheap.size()) { return (maxheap.peek() + minheap.peek()) * 0.5; } else { return maxheap.peek(); } } };
朋友会在“发现-看一看”看到你“在看”的内容