剑指offer题64
来源:互联网 发布:linux驱动书籍 编辑:程序博客网 时间:2024/06/05 17:48
package jianzhioffer;import java.util.Collections;import java.util.Comparator;import java.util.LinkedList;import java.util.PriorityQueue;import java.util.Scanner;/** * 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值, * 那么中位数就是所有数值排序之后位于中间的数值。 * 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 * */public class Solution64 {/*输入为数据流,建立两个堆,一个大顶堆,一个小顶堆,小顶堆的所有元素都大于大顶堆的顶,两个堆的元素个数差值小于等于1. * 当insert的数字个数为奇数时:使小顶堆个数比大顶堆多1; * 当insert的数字个数为偶数时,使大顶堆个数跟小顶堆个数一样。 * 那么当总数字个数为奇数时,中位数就是小顶堆堆头; * 当总数字个数为偶数时,中卫数就是 2个堆堆头平均数 **//*private static PriorityQueue<Integer> min = new PriorityQueue<>();private static PriorityQueue<Integer> max = new PriorityQueue<>(15,new Comparator<Integer>(){public int compare(Integer i,Integer j){return j.compareTo(i);}});private static int count = 0;public static void Insert(Integer num) {count++;if(count%2 == 1){max.offer(num);min.offer(max.poll());}else{min.offer(num);max.offer(min.poll());} } public static Double GetMedian() { if(count%2 == 1){ return (double)min.peek(); }else{ return (min.peek()+max.peek())/2.0; } }public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){ //ctrl+Z 停止接收控制台输入Insert(sc.nextInt());}System.out.println(min.toString());System.out.println(max.toString());System.out.println(GetMedian());}*///直接生成一个链表,每次加入时,进行排序操作。private static LinkedList<Integer> list = new LinkedList<Integer>();public static void Insert(Integer num) { list.add(num); Collections.sort(list); } public static Double GetMedian() { int mid = list.size()/2; if(list.size() % 2 == 0){ return (double)((list.get(mid)+list.get(mid-1))/2); }else{ return (double)list.get(mid); } } public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){Insert(sc.nextInt());}System.out.println(list.toString());System.out.println(GetMedian());}}
阅读全文
0 0
- 剑指offer题64
- 【剑指offer】题64:数据流中的中位数
- 剑指offer第一题
- 剑指offer-题
- 剑指offer第一题
- 剑指Offer第一题
- 剑指offer(题三)
- 剑指offer第二题
- 剑指offer第三题
- 剑指offer第四题
- 剑指offer第五题
- 剑指offer题一
- 剑指offer题二
- 剑指offer题七
- 剑指offer题六
- 【剑指offer】第二题
- 【剑指offer】第三题
- 剑指offer题四
- android 集成Zxing教程
- Hmaster 启动后关闭。
- 语音识别的基础知识与CMUsphinx介绍
- 配置环境变量
- Win10局域网内离线安装sqlserver2012 .net framkwork 3.5问题
- 剑指offer题64
- Spring自动代理
- Catalan number (卡兰特数)
- C++正则表达式匹配工具
- 用c++实现二叉树及堆的数据结构
- Java 代码执行的优先级
- Javabean之动作元素
- Avalon2之VM
- Fastlib网络模块 soap协议解决方案