标签:heap ini sem dia code return https media rev
295 Find Median from Data Stream https://www.youtube.com/watch?v=60xnYZ21Ir0 ///// new PriorityQueue<>(Collections.reverseOrder()); ////. smart public void addNum(int num) { max.offer(num); min.offer(max.poll()); if (max.size() < min.size()){ max.offer(min.poll()); } } ///// class MedianFinder { /** initialize your data structure here. */ PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); PriorityQueue<Integer> minHeap = new PriorityQueue<>(); public MedianFinder() { } public void addNum(int num) { maxHeap.offer(num); if(!minHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){ minHeap.offer(maxHeap.poll()); } if(minHeap.size() > maxHeap.size()){ maxHeap.offer(minHeap.poll()); } if(maxHeap.size() - minHeap.size() > 1){ minHeap.offer(maxHeap.poll()); } } public double findMedian() { if(maxHeap.size() == minHeap.size()){ return (maxHeap.peek() + minHeap.peek()) / 2.0 ; /// 2.0 instead of 2 }else{ return maxHeap.peek(); } } }
295 Find Median from Data Stream
标签:heap ini sem dia code return https media rev
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9454841.html