Google 面试题:Java实现用最大堆和最小堆查找中位数 Find median with min heap and max heap in Java
Google面试题
股市上一个股票的价格从开市开始是不停的变化的,需要开发一个系统,给定一个股票,它能实时显示从开市到当前时间的这个股票的价格的中位数(中值)。
SOLUTION 1:
1.维持两个heap,一个是最小堆,一个是最大堆。
2.一直使maxHeap的size大于minHeap.
3. 当两边size相同时,比较新插入的value,如果它大于minHeap的最大值,把它插入到minHeap。并且把minHeap的最小值移动到maxHeap。
...具体看代码
/**************************************************************
*
* 08-722 Data Structures for Application Programmers
* Lab 7 Heaps and Java PriorityQueue class
*
* Find median of integers using Heaps (maxHeap and minHeap)
*
* Andrew id: yuzhang
* Name: Yu Zhang
*
**************************************************************/ import java.util.*; public class FindMedian {
private static PriorityQueue<Integer> maxHeap, minHeap; public static void main(String[] args) { Comparator<Integer> revCmp = new Comparator<Integer>() {
@Override
public int compare(Integer left, Integer right) {
return right.compareTo(left);
}
}; // Or you can use Collections' reverseOrder method as follows.
// Comparator<Integer> revCmp = Collections.reverseOrder(); maxHeap = new PriorityQueue<Integer>(, revCmp);
minHeap = new PriorityQueue<Integer>(); addNumber();
addNumber();
addNumber();
addNumber();
addNumber();
System.out.println(minHeap);
System.out.println(maxHeap);
System.out.println(getMedian()); addNumber();
System.out.println(minHeap);
System.out.println(maxHeap);
System.out.println(getMedian()); addNumber();
addNumber();
System.out.println(minHeap);
System.out.println(maxHeap);
System.out.println(getMedian());
} /*
* Note: it maintains a condition that maxHeap.size() >= minHeap.size()
*/
public static void addNumber(int value) {
if (maxHeap.size() == minHeap.size()) {
if (minHeap.peek() != null && value > minHeap.peek()) {
maxHeap.offer(minHeap.poll());
minHeap.offer(value);
} else {
maxHeap.offer(value);
}
} else {
if (value < maxHeap.peek()) {
minHeap.offer(maxHeap.poll());
maxHeap.offer(value);
} else {
minHeap.offer(value);
}
}
} /*
* If maxHeap and minHeap are of different sizes,
* then maxHeap must have one extra element.
*/
public static double getMedian() {
if (maxHeap.isEmpty()) {
return -;
} if (maxHeap.size() == minHeap.size()) {
return (double)(minHeap.peek() + maxHeap.peek())/;
} else {
return maxHeap.peek();
}
}
}
SOLUTION 2:
比起solution 1 ,进行了简化
maxHeap保存较小的半边数据,minHeap保存较大的半边数据。
1.无论如何,直接把新值插入到maxHeap。
2. 当minHeap为空,直接退出。
3. 当maxHeap比minHeap多2个值,直接移动一个值到maxHeap即可。
4. 当maxHeap比minHeap多1个值,比较顶端的2个值,如果maxHeap的最大值大于minHeap的最小值,交换2个值即可。
5. 当maxHeap较大时,中值是maxHeap的顶值,否则取2者的顶值的中间值。
/**************************************************************
*
* 08-722 Data Structures for Application Programmers
* Lab 7 Heaps and Java PriorityQueue class
*
* Find median of integers using Heaps (maxHeap and minHeap)
*
* Andrew id: yuzhang
* Name: Yu Zhang
*
**************************************************************/ import java.util.*; public class FindMedian_20150122 {
private static PriorityQueue<Integer> maxHeap, minHeap; public static void main(String[] args) {
// Or you can use Collections' reverseOrder method as follows.
// Comparator<Integer> revCmp = Collections.reverseOrder(); maxHeap = new PriorityQueue<Integer>(, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}); minHeap = new PriorityQueue<Integer>(); addNumber();
addNumber();
addNumber();
addNumber();
addNumber();
System.out.println(minHeap);
System.out.println(maxHeap);
System.out.println(getMedian()); addNumber();
System.out.println(minHeap);
System.out.println(maxHeap);
System.out.println(getMedian()); addNumber();
addNumber();
System.out.println(minHeap);
System.out.println(maxHeap);
System.out.println(getMedian());
} /*
* Note: it maintains a condition that maxHeap.size() >= minHeap.size()
*/
public static void addNumber1(int value) {
if (maxHeap.size() == minHeap.size()) {
if (!maxHeap.isEmpty() && value > minHeap.peek()) {
// put the new value in the right side.
maxHeap.offer(minHeap.poll());
minHeap.offer(value);
} else {
// add the new value into the left side.
maxHeap.offer(value);
}
} else {
if (value < maxHeap.peek()) {
// add the new value into the left side.
minHeap.offer(maxHeap.poll());
maxHeap.offer(value);
} else {
// add the new value into the right side.
minHeap.offer(value);
}
}
} /*
* Note: it maintains a condition that maxHeap.size() >= minHeap.size()
* solution 2:
*/
public static void addNumber(int value) {
maxHeap.offer(value); // For this case, before insertion, max-heap has n+1 and min-heap has n elements.
// After insertion, max-heap has n+2 and min-heap has n elements, so violate!
// And we need to pop 1 element from max-heap and push it to min-heap
if (maxHeap.size() - minHeap.size() == ) {
// move one to the right side.
minHeap.offer(maxHeap.poll());
} else {
if (minHeap.isEmpty()) {
return;
} // If the newly inserted value is larger than root of min-heap
// we need to pop the root of min-heap and insert it to max-heap.
// And pop root of max-heap and insert it to min-heap
if (minHeap.peek() < maxHeap.peek()) {
// exchange the top value in the minHeap and the maxHeap.
minHeap.offer(maxHeap.poll());
maxHeap.offer(minHeap.poll());
}
}
} /*
* If maxHeap and minHeap are of different sizes,
* then maxHeap must have one extra element.
*/
public static double getMedian() {
if (maxHeap.isEmpty()) {
return -;
} if (maxHeap.size() > minHeap.size()) {
return maxHeap.peek();
} else {
return (double)(maxHeap.peek() + minHeap.peek()) / ;
}
}
}
ref: http://blog.csdn.net/fightforyourdream/article/details/12748781
http://www.ardendertat.com/2011/11/03/programming-interview-questions-13-median-of-integer-stream/
http://blog.sina.com.cn/s/blog_979956cc0101hab8.html
http://blog.csdn.net/ajaxhe/article/details/8734280
http://www.cnblogs.com/remlostime/archive/2012/11/09/2763256.html
Google 面试题:Java实现用最大堆和最小堆查找中位数 Find median with min heap and max heap in Java的更多相关文章
- C++ multiset通过greater、less指定排序方式,实现最大堆、最小堆功能
STL中的set和multiset基于红黑树实现,默认排序为从小到大. 定义三个multiset实例,进行测试: multiset<int, greater<int>> gre ...
- c++/java/python priority_que实现最大堆和最小堆
#include<iostream>#include<vector>#include<math.h>#include<string>#include&l ...
- 【Java】 用PriorityQueue实现最大最小堆
PriorityQueue(优先队列),一个基于优先级堆的无界优先级队列. 实际上是一个堆(不指定Comparator时默认为最小堆),通过传入自定义的Comparator函数可以实现大顶堆. Pri ...
- PAT-1147(Heaps)最大堆和最小堆的判断+构建树
Heaps PAT-1147 #include<iostream> #include<cstring> #include<string> #include<a ...
- -Xmx 和 –Xms 设置最大堆和最小堆
C:\Java\jre1.6.0\bin\javaw.exe 按照上面所说的,最后参数在eclipse.ini中可以写成这个样子: -vmargs -Xms128M -Xmx512M ...
- STL 最大堆与最小堆
在第一场CCCC选拔赛上,有一关于系统调度的水题.利用优先队列很容易AC. // 由于比赛时花费了不少时间研究如何定义priority_queue的比较函数,决心把STL熟练掌握... Queue 首 ...
- Java编程的逻辑 (45) - 神奇的堆
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...
- Java生产环境JVM设置成固定堆大小深层原理
可能很多人都知道Java程序上生产后,运维人员都会设定好JVM的堆大小,而且还是把最大最小设置成一样的值.那究竟是为什么呢?一般而言,Java程序如果你不显示设定该值得话,会自动进行初始化设定. -X ...
- java最大最小堆
堆是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于(或不小于)其左孩子和右孩子节点的值. 最大堆和最小堆是二叉堆的两种形式. 最大堆:根结点的键值是所有堆结点键值中最大者. 最小堆:根结 ...
随机推荐
- International Conference in 2015
Call for Paper International Conference on Computer Vision(ICCV2015, Santiago, Chile). (deadline: Ap ...
- 毫无保留开源我写的:IOS Android Ipad 多点触摸通用js 库
毫无保留开源我写的:IOS Android Ipad 多点触摸通用js 库 在线演示地址: http://m.yunxunmi.com/ 支持 IOS Android Ipad 等不同操作系统的手持或 ...
- 编译nginx的源码安装subs_filter模块
使用nginx的反向代理功能搭建nuget镜像服务器时,需要针对官方nuget服务器的响应内容进行字符串替换,比如将www.nuget.org替换为镜像服务器的主机名,将https://替换为http ...
- [JS1] 如何嵌入
<html> <head> <title>在HTML文档中嵌入JavaScript代码是如何嵌入到HTML文档中的.</title> <scrip ...
- [ucgui] 对话框3——GUIBuilder生成界面c文件及修改
>_<" 其实生成GUI有相应的工具:
- 只有好的棋手才会走运-《打造Facebook》读后感
王淮的<打造Facebook>一书不厚,花半天时间轻松读完.书中没有大段的说教,只有近乎流水的陈述.正如作者所说,打造Facebook这本书由巴克伯格来写再合适不过.可惜他至少在近几年内没 ...
- C++ 标准库类型-String,Vector and Bitset
<C++ Primer 4th>读书摘要 最重要的标准库类型是 string 和 vector,它们分别定义了大小可变的字符串和集合.这些标准库类型是语言组成部分中更基本的那些数据类型(如 ...
- centos 关闭防火墙
在centos上搭建了个服务器,本机可以访问,局域网无法访问 解决方案:关闭防火墙 sudo systemctl stop firewalld.service 令人恼火的是stop iptables之 ...
- spring源码 — 三、AOP代理生成
AOP代理生成 AOP就是面向切面编程,主要作用就是抽取公共代码,无侵入的增强现有类的功能.从一个简单的spring AOP配置开始: <?xml version="1.0" ...
- SQL Server 内存中OLTP内部机制概述(四)
----------------------------我是分割线------------------------------- 本文翻译自微软白皮书<SQL Server In-Memory ...