标签:
原题链接在这里:https://leetcode.com/problems/find-median-from-data-stream/
维护两个堆,一个maxHeap用来存较小的一半数,一个minHeap用来存较大的一半数。每次添加时看minHeap的root是不是小于 num, 若是就把num加在minHeap上,若不然就看看maxHeap的root是不是大于num, 若是就把num加在maxHeap上面,若是两种情况都不符合就加在minHeap上。
加完后需要balance 两个heap的大小,若size相差大于1, size大的给size小的一个。
findMedian 取size 较大heap的root, 若是size相同,一边取一个算平均数。
AddNum() Time Complexity: O(logn); findMedian() Time Complexity: O(1).
AC Java:
1 class MedianFinder { 2 PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); 3 PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder()); 4 // Adds a number into the data structure. 5 public void addNum(int num) { 6 if(minHeap.size() > 0 && num > minHeap.peek()){ 7 minHeap.add(num); 8 }else if(maxHeap.size() > 0 && num < maxHeap.peek()){ 9 maxHeap.add(num); 10 }else{ 11 minHeap.add(num); 12 } 13 14 //Rebalance two heaps 15 if(minHeap.size() - maxHeap.size() > 1){ 16 maxHeap.add(minHeap.poll()); 17 } 18 if(maxHeap.size() - minHeap.size() > 1){ 19 minHeap.add(maxHeap.poll()); 20 } 21 } 22 23 // Returns the median of current data stream 24 public double findMedian() { 25 if(maxHeap.size() > minHeap.size()){ 26 return (double) maxHeap.peek(); 27 }else if(minHeap.size() > maxHeap.size()){ 28 return (double) minHeap.peek(); 29 }else{ 30 return (double)(maxHeap.peek()+minHeap.peek())/2.0; 31 } 32 } 33 };
LeetCode Find Median from Data Stream
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4934939.html