题目描述
数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。
思路
用一个大顶堆一个小顶堆即可。
参考:滑动窗口的中位数
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| class Help implements Comparable<Help>{ public int val; public Help(int val) { this.val = val; }
@Override public int compareTo(Help o) { // TODO Auto-generated method stub return this.val < o.val ? 1 : this.val > o.val ? -1 : 0; } } public int[] medianII(int[] nums) { // init int[] ret = new int[nums.length]; PriorityQueue<Integer> minHeap = new PriorityQueue<>(); PriorityQueue<Help> maxHeap = new PriorityQueue<>(); ret[0] = nums[0]; maxHeap.add(new Help(nums[0])); // find mid after first for(int i = 1; i < nums.length; i++) { if(nums[i] > maxHeap.peek().val) { minHeap.add(nums[i]); }else { maxHeap.add(new Help(nums[i])); } if(i % 2 == 0) { if(maxHeap.size() > minHeap.size()) { while((maxHeap.size() - minHeap.size()) != 1) { minHeap.add(maxHeap.poll().val); } ret[i] = maxHeap.peek().val; }else { while((maxHeap.size() - minHeap.size()) != 1) { maxHeap.add(new Help(minHeap.poll())); } ret[i] = maxHeap.peek().val; } }else { if(maxHeap.size() > minHeap.size()) { while(maxHeap.size() != minHeap.size()) { minHeap.add(maxHeap.poll().val); } ret[i] = maxHeap.peek().val; }else { while(maxHeap.size() != minHeap.size()) { maxHeap.add(new Help(minHeap.poll())); } ret[i] = maxHeap.peek().val; } } } return ret; }
|
考差点