题目 一个数据流中,随时可以取得中位数。
思路 同https://blog.csdn.net/Dorothy_Xue/article/details/105348997 只是此处的堆结构不是自己构造的。
package algorithm.section7;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MedianQuick {
private PriorityQueue<Integer> min = new PriorityQueue<>(new maxComparator());
private PriorityQueue<Integer> max = new PriorityQueue<>(new minComparator());
public static class minComparator implements Comparator<Integer> {
@Override
public int compare(Integer t1, Integer t2) {
if (t2 > t1) return 1;
else return -1;
}
}
public static class maxComparator implements Comparator<Integer> {
@Override
public int compare(Integer t1, Integer t2) {
if (t1 > t2) return 1;
else return -1;
}
}
public void addNum(int num){
if (this.max.isEmpty()) {
this.max.add(num);
return;
} else {
if (num > this.max.peek()) this.min.add(num);
else this.max.add(num);
}
if (this.max.size() - this.min.size() > 1) this.min.add(this.max.poll());
if (this.min.size() - this.max.size() > 1) this.max.add(this.min.poll());
}
public float getMedian () {
if (this.max.size() == 0 && this.min.size() == 0) return 0;
if (this.min.size() == this.max.size()) return (float)(this.min.peek() + this.max.peek()) / 2;
else return this.min.size() > this.max.size() ? min.peek() : max.peek();
}
// for test
public static int[] getRandomArray(int maxLen, int maxValue) {
int[] res = new int[(int) (Math.random() * maxLen) + 1];
for (int i = 0; i != res.length; i++) {
res[i] = (int) (Math.random() * maxValue);
}
return res;
}
// for test, this method is ineffective but absolutely right
public static int getMedianOfArray(int[] arr) {
int[] newArr = Arrays.copyOf(arr, arr.length);
Arrays.sort(newArr);
int mid = (newArr.length - 1) / 2;
if ((newArr.length & 1) == 0) {
return (newArr[mid] + newArr[mid + 1]) / 2;
} else {
return newArr[mid];
}
}
public static void printArray(int[] arr) {
for (int i = 0; i != arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {}
}