21.03.11 LeetCode295. 数据流的中位数
作者:互联网
中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
示例:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
class MedianFinder { /** initialize your data structure here. */ private PriorityQueue<Integer> big; private PriorityQueue<Integer> small; public MedianFinder() { big = new PriorityQueue<>(new MaxHeapComparator()); small = new PriorityQueue<>(new MinHeapComparator()); } //先写大根堆和小根堆的排序规则 public static class MaxHeapComparator implements Comparator<Integer> { public int compare(Integer o1,Integer o2) { if(o2>o1) return 1; else { return-1; } } } public static class MinHeapComparator implements Comparator<Integer> { public int compare(Integer o1,Integer o2) { if(o2<o1) return 1; else { return -1; } } } //调整大小根堆的大小 public void modifyData() { //对比大小根堆的大小 if(this.big.size() == this.small.size() +2 ) this.small.add( this.big.poll() ); if(this.small.size() == this.big.size() +2 ) this.big.add(this.small.poll() ); } public void addNum(int num) { if(this.big.isEmpty()) { this.big.add(num); return; } if(this.big.peek()>=num) { this.big.add(num); } else{ if(this.small.isEmpty()) { small.add(num); } else{ if(small.peek()>num) { this.big.add(num); } else{this.small.add(num);} } } modifyData(); } public double findMedian() { int maxSize = this.big.size(); int minSize = this.small.size(); if(maxSize+minSize==0) return 0; double maxMedian = this.big.isEmpty()? 0:this.big.peek(); double minMedian = this.small.isEmpty()?0:this.small.peek() ; double res = (maxMedian+minMedian)/2; if ( (maxSize+minSize) %2!=1 )//序列是否为偶数 return res; return maxSize>minSize?maxMedian:minMedian; } }
标签:11,LeetCode295,int,big,中位数,num,21.03,small,public 来源: https://www.cnblogs.com/pionice/p/14516527.html