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()) / ;
}
}
}

GITHUB: https://github.com/yuzhangcmu/08722_DataStructures/blob/master/08722_LAB7/src/FindMedian_20150122.java

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的更多相关文章

  1. C++ multiset通过greater、less指定排序方式,实现最大堆、最小堆功能

    STL中的set和multiset基于红黑树实现,默认排序为从小到大. 定义三个multiset实例,进行测试: multiset<int, greater<int>> gre ...

  2. c++/java/python priority_que实现最大堆和最小堆

    #include<iostream>#include<vector>#include<math.h>#include<string>#include&l ...

  3. 【Java】 用PriorityQueue实现最大最小堆

    PriorityQueue(优先队列),一个基于优先级堆的无界优先级队列. 实际上是一个堆(不指定Comparator时默认为最小堆),通过传入自定义的Comparator函数可以实现大顶堆. Pri ...

  4. PAT-1147(Heaps)最大堆和最小堆的判断+构建树

    Heaps PAT-1147 #include<iostream> #include<cstring> #include<string> #include<a ...

  5. -Xmx 和 –Xms 设置最大堆和最小堆

    C:\Java\jre1.6.0\bin\javaw.exe 按照上面所说的,最后参数在eclipse.ini中可以写成这个样子: -vmargs     -Xms128M     -Xmx512M ...

  6. STL 最大堆与最小堆

    在第一场CCCC选拔赛上,有一关于系统调度的水题.利用优先队列很容易AC. // 由于比赛时花费了不少时间研究如何定义priority_queue的比较函数,决心把STL熟练掌握... Queue 首 ...

  7. Java编程的逻辑 (45) - 神奇的堆

    本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...

  8. Java生产环境JVM设置成固定堆大小深层原理

    可能很多人都知道Java程序上生产后,运维人员都会设定好JVM的堆大小,而且还是把最大最小设置成一样的值.那究竟是为什么呢?一般而言,Java程序如果你不显示设定该值得话,会自动进行初始化设定. -X ...

  9. java最大最小堆

    堆是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于(或不小于)其左孩子和右孩子节点的值. 最大堆和最小堆是二叉堆的两种形式. 最大堆:根结点的键值是所有堆结点键值中最大者. 最小堆:根结 ...

随机推荐

  1. poj3468 A Simple Problem with Integers (线段树区间最大值)

    A Simple Problem with Integers Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 92127   ...

  2. delphi 获取颜色值的RGB

    前言:http://www.cnblogs.com/studypanp/p/5002953.html 获取的颜色值 前面获取到一个像素点的颜色值后(十六进制),比如说(黄色):FFD1C04C(共八位 ...

  3. C#设计模式(10)——组合模式(Composite Pattern)

    一.引言 在软件开发过程中,我们经常会遇到处理简单对象和复合对象的情况,例如对操作系统中目录的处理就是这样的一个例子,因为目录可以包括单独的文件,也可以包括文件夹,文件夹又是由文件组成的,由于简单对象 ...

  4. 基于Qt的流程设计器(一)

    一: 先来看一下界面的截图:   说明: 拖动节点的时候,与该节点相关的箭头连线也会跟着调整: 用户可以使用鼠标从一个节点拖出一个箭头到另一个节点(鼠标在空白区域点击一下,拖出的箭头消失)   这三个 ...

  5. Android-Universal-Image-Loader三大组件DisplayImageOptions、ImageLoader、ImageLoaderConfiguration详解

    一.介绍 Android-Universal-Image-Loader是一个开源的UI组件程序,该项目的目的是提供一个可重复使用的仪器为异步图像加载,缓存和显示.所以,如果你的程序里需要这个功能的话, ...

  6. 架构模式对象与关系结构模式之:标识域(Identity Field)

    一:标识域(Identity Field) 标识域(Identity Field)可以理解为主键.使用领域模型和行数据入口的时候,就要使用标识域,因为这两个对象代表的是唯一存在的那个数据记录.事务脚本 ...

  7. [游戏模版3] Win32 画笔 画刷 图形

    >_<:introduce the functions of define\create\use pen and brush to draw all kinds of line and s ...

  8. Unity3d碰撞检测中碰撞器与触发器的区别

    要产生碰撞必须为游戏对象添加刚体(Rigidbody)和碰撞器,刚体可以让物体在物理影响下运动.碰撞体是物理组件的一类,它要与刚体一起添加到游戏对象上才能触发碰撞.如果两个刚体相互撞在一起,除非两个对 ...

  9. Java-基础练习1

    1.      Java为什么能跨平台运行?请简述原理. 因为Java程序编译之后的代码不是能被硬件系统直接运行的代码,而是一种“中间码”——字节码.然后不同的硬件平台上安装有不同的Java虚拟机(J ...

  10. DataGridView列排序混乱的处理方法

    在C#程序开发中DataGridView可以说是使用最多的数据呈现控件了,但是在使用的过程中我们会发现当绑定的数据源有较多数据列的时候,DataGridView上显示的列的顺序就会出现混乱的现象. 那 ...