您的位置:首页 > 其它

Find Median With Two heaps

2013-11-14 02:17 375 查看
Numbers are randomly generated and passed to a method. Write a program to find and maintain the median values as new values are generated.

public int solution(int[] a) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>();
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
Arrays.sort(a);
int i = 0;
for(; i <= a.length / 2; i++) {
maxHeap.add(a[i]);
}
for(; i < a.length; i++) {
minHeap.add(a[i]);
}
return getMedian(maxHeap, minHeap);
}

public int getMedian(PriorityQueue<Integer> maxHeap, PriorityQueue<Integer> minHeap) {
if(maxHeap.isEmpty()) return 0;
//maxHeap will always big than or equal to minHeap
else if(maxHeap.size() == minHeap.size()) return (maxHeap.peek() + minHeap.peek()) / 2;
else return maxHeap.peek();
}

public void add(PriorityQueue<Integer> maxHeap, PriorityQueue<Integer> minHeap, int number) {
if(maxHeap.size() == minHeap.size()) {
if(minHeap.peek() != null && number > minHeap.peek()) {
//if number should add to minHeap
//then we should move the top to max
maxHeap.add(minHeap.remove());
minHeap.add(number);
} else {
maxHeap.add(number);
}
}else {
//max has a large size
//which means maxHeap should not be empty
if(maxHeap.peek() < number) {
minHeap.add(maxHeap.remove());
maxHeap.add(number);
}else {
minHeap.add(number);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: