LintCode-Median II
Numbers keep coming, return the median of numbers at every time a new number added.
For numbers coming list: [1, 2, 3, 4, 5], return [1, 1, 2, 2, 3]
For numbers coming list: [4, 5, 1, 3, 2, 6, 0], return [4, 4, 4, 3, 3, 3, 3]
For numbers coming list: [2, 20, 100], return [2, 2, 20]
O(nlogn) time
Clarification
What's the definition of Median?
- Median is the number that in the middle of a sorted array. If there are n numbers in a sorted array A, the median is A[(n-1)/2].
- For example, if A=[1,2,3], median is 2. If A=[1,19], median is 1
Analysis:
We maintain a max heap and a min heap. At any index i, the max heap stores the elements small or equal than the current median and the min heap stores the elements that are larger than the current median. Because in the problem, we select the median as at the position (n-1)/2, so we should always keep the size of max heap equal or one larger than the min heap. At odd index, we try to rebalance the size of max heap and min heap, while at even index, we try to make the size of max heap one larger than that of the min heap. By doing this, at each position, after inserting A[i] into the heaps, the root value of the max heap is the median.
NOTE: if we select (n-1)/2+1 as median, we can then keep the min heap equal or one larger than the max heap, the root value of the min heap is the median.
Solution:
I implement a Heap class with only insert and popHeapRoot functions.
class Heap{
private int[] nodes;
private int size;
private boolean isMaxHeap; public Heap(int capa, boolean isMax){
nodes = new int[capa];
size = 0;
isMaxHeap = isMax;
} public boolean isEmpty(){
if (size==0) return true;
else return false;
} public int getHeapRootValue(){
//should throw exception when size==0;
return nodes[0];
} private void swap(int x, int y){
int temp = nodes[x];
nodes[x] = nodes[y];
nodes[y] = temp;
} public boolean insert(int val){
if (size==nodes.length) return false;
size++;
nodes[size-1]=val;
//check its father iteratively.
int cur = size-1;
int father = (cur-1)/2;
while (father>=0 && ((isMaxHeap && nodes[cur]>nodes[father]) || (!isMaxHeap && nodes[cur]<nodes[father]))){
swap(cur,father);
cur = father;
father = (cur-1)/2;
}
return true;
} private void shiftDown(int ind){
int left = (ind+1)*2-1;
int right = (ind+1)*2;
while (left<size || right<size){
if (isMaxHeap){
int leftVal = (left<size) ? nodes[left] : Integer.MIN_VALUE;
int rightVal = (right<size) ? nodes[right] : Integer.MIN_VALUE;
int next = (leftVal>=rightVal) ? left : right;
if (nodes[ind]>nodes[next]) break;
else {
swap(ind,next);
ind = next;
left = (ind+1)*2-1;
right = (ind+1)*2;
}
} else {
int leftVal = (left<size) ? nodes[left] : Integer.MAX_VALUE;
int rightVal = (right<size) ? nodes[right] : Integer.MAX_VALUE;
int next = (leftVal<=rightVal) ? left : right;
if (nodes[ind]<nodes[next]) break;
else {
swap(ind,next);
ind = next;
left = (ind+1)*2-1;
right = (ind+1)*2;
}
}
}
} public int popHeapRoot(){
//should throw exception, when heap is empty. int rootVal = nodes[0];
swap(0,size-1);
size--;
if (size>0) shiftDown(0);
return rootVal;
}
} public class Solution {
/**
* @param nums: A list of integers.
* @return: the median of numbers
*/
public int[] medianII(int[] nums) {
int[] res = new int[nums.length];
Heap maxHeap = new Heap(nums.length,true);
Heap minHeap = new Heap(nums.length,false);
maxHeap.insert(nums[0]);
res[0] = nums[0];
for (int i=1;i<nums.length;i++)
if (i %2 == 1) { //i is odd index.
int median = maxHeap.getHeapRootValue();
if (nums[i]<median){
maxHeap.popHeapRoot();
minHeap.insert(median);
maxHeap.insert(nums[i]);
res[i] = maxHeap.getHeapRootValue();
} else {
res[i] = median;
minHeap.insert(nums[i]);
}
} else { //i is even index.
int median = maxHeap.getHeapRootValue();
if (nums[i]<median){
maxHeap.insert(nums[i]);
} else {
minHeap.insert(nums[i]);
int val = minHeap.popHeapRoot();
maxHeap.insert(val);
}
res[i] = maxHeap.getHeapRootValue();
} return res;
}
}
LintCode-Median II的更多相关文章
- [LintCode] Median of Two Sorted Arrays 两个有序数组的中位数
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted ...
- Lintcode: Median
Given a unsorted array with integers, find the median of it. A median is the middle number of the ar ...
- [LintCode] Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations ...
- LintCode: Median of two Sorted Arrays
求第k个值 1.归并排序 归并到第k个值为止 时间复杂度:O(k) class Solution { public: // merge-sort to find K-th value double h ...
- [算法专题] 深度优先搜索&回溯剪枝
1. Palindrome Partitioning https://leetcode.com/problems/palindrome-partitioning/ Given a string s, ...
- lintcode 最长上升连续子序列 II(二维最长上升连续序列)
题目链接:http://www.lintcode.com/zh-cn/problem/longest-increasing-continuous-subsequence-ii/ 最长上升连续子序列 I ...
- Lintcode: Sort Colors II 解题报告
Sort Colors II 原题链接: http://lintcode.com/zh-cn/problem/sort-colors-ii/# Given an array of n objects ...
- Lintcode: Majority Number II 解题报告
Majority Number II 原题链接: http://lintcode.com/en/problem/majority-number-ii/# Given an array of integ ...
- leetcode 293.Flip Game(lintcode 914) 、294.Flip Game II(lintcode 913)
914. Flip Game https://www.cnblogs.com/grandyang/p/5224896.html 从前到后遍历,遇到连续两个'+',就将两个加号变成'-'组成新的字符串加 ...
- Lintcode 150.买卖股票的最佳时机 II
------------------------------------------------------------ 卧槽竟然连题意都没看懂,百度了才明白题目在说啥....我好方啊....o(╯□ ...
随机推荐
- PHP插件技术-插件钩子(hooks)分析
最近准备做一个开源的个人博客系统,因为在构想中要添加插件功能,所以就研究了一下插件功能的实现方法. 插件的功能按照本人自己的理解就是对已有的程序进行功能方面的添加以及改进,插件要与程序所提供的接口进行 ...
- 第十一篇、微信小程序-input组件
主要属性: 效果图: ml: <!--style的优先级比class高会覆盖和class相同属性--> <!--头像--> <view style="displ ...
- jqure全选/取消
平时我们会遇到全选/全取消, 前台效果: <div class="fix pb40 mt32 ml30 lh22"> <div class="l mr2 ...
- (转)Yale CAS + .net Client 实现 SSO(6)
第一部分:安装配置 Tomcat 第二部分:安装配置 CAS 第三部分:实现 ASP.NET WebForm Client 第四部分:实现基于数据库的身份验证 第五部分:扩展基于数据库的身份验证 第六 ...
- hdu 2544 最短路 Dijkstra
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544 题目分析:比较简单的最短路算法应用.题目告知起点与终点的位置,以及各路口之间路径到达所需的时间, ...
- 几道hihocoder不会做的题
1.https://hihocoder.com/problemset/problem/1433?sid=970287 boarding passes,不会做,看的别人的代码,现在还不是很理解. 2. ...
- windows phone 8 开发系列(一)环境搭建
一:前奏说明 本人一名普通的neter,对新玩意有点小兴趣,之前wp7出来的时候,折腾学习过点wp7开发,后来也没怎么用到(主要对微软抛弃wp7的行为比较不爽),现在wp8已经出来一段时间了,市场上也 ...
- 《linux文件权限管理大总结》RHEL6
在linux系统下文件的权限通常会以下面的格式显示出来: Chmod文件权限: 权限的管理chmod -a 所有的权限 -u 文件所有者的权限 -g 组权限 -o 其他用户的权限 可以使用运算符来设 ...
- WCF 配置文件(三)
配置文件概述 WCF服务配置是WCF服务编程的主要部分.WCF作为分布式开发的基础框架,在定义服务以及定义消费服务的客户端时,都使用了配置文件的方法.虽然WCF也提供硬编程的方式,通过在代码中直接设置 ...
- 前端工程搭建NodeJs+gulp+bower
需要node.npm的事先安装!! 1.nodejs安装程序会在环境变量中添加两个变量: 系统环境变量中:path 增加C:\Program Files\nodejs\ 因为在该目下存在node.ex ...