数据流中的中位数
简单直接—用list存储,调用sort方法排序。
class MedianFinder {
ArrayList< Integer> arrayList;
public MedianFinder ( ) {
arrayList = new ArrayList < > ( ) ;
}
public void addNum ( int num) {
arrayList. add ( num) ;
}
public double findMedian ( ) {
int size = arrayList. size ( ) ;
Collections. sort ( arrayList) ;
if ( size % 2 == 1 ) {
return arrayList. get ( size / 2 ) ;
}
else {
int index = size / 2 ;
int n1 = arrayList. get ( index) ;
int n2 = arrayList. get ( index - 1 ) ;
return ( n1 + n2) / 2.0 ;
}
}
}
用大根堆和小根堆存储数据流中元素。 大根堆存储比小根堆存储元素多1,并且大根堆元素小于小根堆元素。 如果N为奇数,大根堆堆顶元素为中位数。 如果N为偶数,大根堆堆顶元素和小根堆堆顶元素和的平均值为中位数。
class MedianFinder {
PriorityQueue< Integer> min_heap;
PriorityQueue< Integer> max_heap;
public MedianFinder ( ) {
min_heap = new PriorityQueue < > ( ) ;
max_heap = new PriorityQueue < > ( ( o1, o2) - > o2 - o1) ;
}
public void addNum ( int num) {
max_heap. add ( num) ;
if ( ! min_heap. isEmpty ( ) && max_heap. peek ( ) > min_heap. peek ( ) ) {
int x = min_heap. poll ( ) ;
int y = max_heap. poll ( ) ;
min_heap. add ( y) ;
max_heap. add ( x) ;
}
if ( max_heap. size ( ) > min_heap. size ( ) + 1 ) {
min_heap. add ( max_heap. poll ( ) ) ;
}
}
public double findMedian ( ) {
if ( ( min_heap. size ( ) + max_heap. size ( ) & 1 ) == 1 ) {
return max_heap. peek ( ) ;
}
else {
int x1 = min_heap. peek ( ) ;
int x2 = max_heap. peek ( ) ;
return ( x1 + x2) / 2.0 ;
}
}
}