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. poj 3635/hdu 1676 Full Tank? 车辆加油+最短路

    http://acm.hdu.edu.cn/showproblem.php?pid=1676 给出一张图,n<=1000,m<=10000. 有一辆车想从图的一个地方到达另外一个地方,每个 ...

  2. SQL Server 利用锁提示优化Row_number()-程序员需知

    网站中一些老页面仍采用Row_number类似的开窗函数进行分页处理,此时如果遭遇挖坟帖的情形可能就需要漫长的等待且消耗巨大.这里给大家介绍根据Row_number()特性采用特定锁Hint提升查询速 ...

  3. 在SSMS里批量删除表、存储过程等各种对象

    在SSMS里批量删除表.存储过程等各种对象 以前想找批量删除表或者存储过程的方法,原来SSMS的GUI界面也可以完成 请看下图,因为这次出差的时候要删除所有的存储过程,然后重建这些存储过程 而表.函数 ...

  4. Orchard Platform v1.7.2 发布

    发布说明: 1. 添加Json格式数据文件支持.2. 删除了Settings, Modules, Themes模块中的Routers和Controllers.3. 删除了默认的ContentType, ...

  5. addin 笔记

    http://msdn.microsoft.com/en-us/library/vstudio/19dax6cz.aspx VS 加载插件的位置: \My Documents\Visual Studi ...

  6. 借助阿里AntUI元素实现两个Web页面之间的过渡——“Loading…”

    今天遇到了这么个问题,如下: 功能需求:有两个页面A和B,点击A中的"确定"按钮,超链接到页面B,在跳转到B页面时出现“Loading”的样式. 需求分析:作为一个后端程序员,一开 ...

  7. 自己动手写UI库——引入ExtJs(布局)

    第一: 来看一下最终的效果 第二: 来看一下使用方法: 第三: Component类代码如下所示: public class Component     {                   pub ...

  8. Hash与Map

    Hash与Map 面试时经常被问到,什么是Hash?什么是Map? 答:hash采用hash表存储,map一般采用红黑树(RB Tree)实现.因此其memory数据结构是不一样的,而且他们的时间复杂 ...

  9. VS2015详细安装步骤

    亲身经历记录下来,以备后用.也希望能够帮助到有需要的朋友们! 1.安装之前首先下载VS2015,下载地址: [VS2015社区版官方中文版下载]:http://download.microsoft.c ...

  10. ASP.NET Entity Framework with MySql服务器发布环境配置

    首先,.net应该自带Entity Framework,所以服务器只要有对应版本的.net Framework就OK! 我们在开发环境中一般会直接使用edmx来管理应用程序与数据库的交互操作,所有与数 ...