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);
}
}
}
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);
}
}
}
相关文章推荐
- keepalived
- 关于 C# 中接口的一些小结
- LeetCode 之 Minimum Depth of Binary Tree
- 工作三个月总结1
- MFC学习记录--从win32程序到MFC
- 初识windows编程之动态链接库
- PHP扩展开发-01:第一个扩展
- DIV+CSS_1_兼容问题
- vim中copy或者delete的技巧
- SSD8 exercise01
- Android—文件进行数据存储(四中操作模式)
- Android 应用开发 之使用LruCache和DiskLruCache来在内存和SD卡中缓存图片
- DIV+CSS_1_样式表的分类
- cin、cin.get()、cin.getline()、getline()、gets()等函数的用法
- 9.png图片制作 — 图文详解
- 自增运算符
- LeetCode题解:Insertion Sort List
- Java 单例模式探讨
- 函数栈及缓冲区溢出攻击(一)
- JAVA 工厂模式简单例子