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(╯□ ...
随机推荐
- asp.net MVC dropList 绑定
废话我就不多说了..上个图.给自己备忘一下
- Mac OSX系统搭建React natvie for android 开发环境
1.下载node.js https://nodejs.org/en/ 下载OSX版本 V5.6 2.安装android SDK JDK 3.安装react-native-cli 打开命令行,输 ...
- 四.CSS声明
概述 一条CSS规则包括选择符和声明两个部分,声明又包括属性和值,属性指出要影响样式的那个方面,而值用于把属性设定成什么 每个HTML元素有很多属性,可以用CSS来设定,但值却只有少数的几种 CSS属 ...
- CCNA长语
思科认证网络支持工程师(Cisco Certified Network Associate_CCNA) 专业英文词汇大全 10BaseT-----原始IEEE802.3标准的一部分,1OBaseT是1 ...
- ios开发:Core Data概述
Core Data 概述 2005年的四月份,Apple 发布了 OS X 10.4,在这个版本中 Core Data 框架发布了.Core Data本身既不是数据库也不是数据库访问框架.相反,Cor ...
- MVC5 属性路由
属性路由(attribute routing)是最新被引进到MVC5中的,它和传统路由共同组成了mvc5中的两种主要路由. 1. 高质量的url应该满足以下几点 域名便于记忆和拼写 简短 便于输入 可 ...
- 单机版简单弹幕墙demo (jqery+bootstrap)
最近在看fcc ,上面有一个弹幕墙设计的题目,要求从后端获取数据,显示出来.百度,谷歌都没找到相关好的例子作为借鉴,索性按照自己的思路写了一个简单的demo .在做demo的过程中遇到最大的问题就 ...
- Codevs 1380 没有上司的舞会
时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description Ural大学有N个职员,编号为1~N.他们有从属关系,也就是说他们的关系就 ...
- 转帖:使用TortoiseGit处理代码冲突
原址:http://www.cnblogs.com/jason-beijing/p/5718190.html 场景一 user0 有新提交 user1 没有pull -> 写新代码 -&g ...
- curl raise 信号出core
在使用c++多线程使用libcurl抓取网页时,遇到程序随机core掉的情况,gdb 一下出错信息有这么一条:longjmp causes uninitialized stack frame. 在网上 ...