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(╯□ ...
随机推荐
- nodejs5-package.json
name:包名,唯一,由小写字符.数字和下划线组成,不能有空格 preferglobal:是否支持全局安装,true表示支持 descrition:描述 version:版本号 author:作者信息 ...
- 自定义View(一)-ViewGroup实现优酷菜单
自定义View的第一个学习案例 ViewGroup是自动以View中比较常用也比较简单的一种方式,通过组合现有的UI控件,绘制出一个全新的View 效果如下: 主类实现如下: package com. ...
- php学习笔记1--开发环境搭建:apache+php+mysql
php开发环境搭建:apache + php + mysql1.下载apache,php及mysql安装包2.安装apache:下载的apache若是.msi可直接双击,按指示一步一步安装:(若操作系 ...
- 解决ASP.NET MVC3与FusionCharts乱码问题
程序代码 代码如下 复制代码 <script type="text/javascript"> $(document).ready(function () { ...
- 通信行业OSS支撑系统软件研发思考
一般的,对所谓大型.通信行业.OSS支撑软件系统,我们可宏观定义以下几点: 以年计的研发周期 以几十人计的研发团队 以百计的业务菜单功能点 以千计的数据库表 以万计的业务术语指标 以亿计的数据表记录 ...
- python简单爬虫编写
1.主要学习这程序的编写思路 a.读取解释网站 b.找到相关页 c.找到图片链接的元素 d.保存图片到文件夹 ..... 将每一个步骤都分解出来,然后用函数去实现,代码易读性高. ##代码尽快运行时会 ...
- IE8 textarea 滚动条定位不准解决方法
工作中遇到一个bug: IE8 下textarea 如果带滚动条(height:100px;overflow:scroll-y;),内容高度超过可视区域之后,输入文字,滚动条位置会乱跳. 开始以为是j ...
- (转)Couchbase介绍,更好的Cache系统
在移动互联网时代,我们面对的是更多的客户端,更低的请求延迟,这当然需要对数据做大量的 Cache 以提高读写速度. 术语 节点:指集群里的一台服务器. 现有 Cache 系统的特点 目前业界使用得最多 ...
- SecureCRT远程控制ubuntu
如果你拥有两台电脑一台是ubuntu,另一台是笔记本电脑,而你又想在远程控制你的ubuntu,那么SecureCRT就可以用了. 1:首先在你的ubuntu电脑上安装SSH服务 :apt-get i ...
- Java HttpURLConnection 抓取网页内容 解析gzip格式输入流数据并转换为String格式字符串
最近GFW为了刷存在感,搞得大家是头晕眼花,修改hosts 几乎成了每日必备工作. 索性写了一个小程序,给办公室的同事们分享,其中有个内容 就是抓取网络上的hosts,废了一些周折. 我是在一个博客上 ...