NC131:随时找到数据流的中位数
随时找到数据流的中位数
http://www.nowcoder.com/questionTerminal/8c5e99acb1fa4bc3a342cd321100c0cd
构造两个优先级队列:左边大根堆放较小的数,右边小根堆放较大的数。
构建两个堆,左边大根堆放较小的数,右边小根堆放较大的数。
插入第一个数时,先插到左边,然后将左边最大的值传给右边的堆;
插入第二个数时,先插到右边,然后将右边最小的值传给左边的堆;
如此往复,平衡两个堆的大小,最后得到的结果是右边堆的值都比左边的大。import java.util.*; public class Solution { /** * the medians * @param operations int整型二维数组 ops * @return double浮点型一维数组 */ public double[] flowmedian (int[][] operations) { // write code here ArrayList<Double> arr = new ArrayList<>(); PriorityQueue<Integer> maxHeap=new PriorityQueue<>(new Comparator<Integer>(){ public int compare(Integer a,Integer b){ return b.compareTo(a); } }); PriorityQueue<Integer> minHeap=new PriorityQueue<>(new Comparator<Integer>(){ public int compare(Integer a,Integer b){ return a.compareTo(b); } }); // PriorityQueue<Integer> maxHeap1=new PriorityQueue<>((a,b)->b.compareTo(a)); // PriorityQueue<Integer> minHeap1=new PriorityQueue<>((a,b)->a.compareTo(b)); // PriotityQueue<Integer> minHeap2=new PriorityQueue<>(); for(int[] op : operations){ if(op[0]==1){ if(maxHeap.isEmpty() || maxHeap.peek()>op[1]){ maxHeap.add(op[1]); } else{ minHeap.add(op[1]); } if(minHeap.size() == maxHeap.size()+2){ maxHeap.add(minHeap.poll()); } if(minHeap.size()+2 == maxHeap.si***Heap.add(maxHeap.poll()); } } else{ if(maxHeap.size()==0){ double ans=-1; arr.add(ans); continue; } if(maxHeap.si***Heap.size()){ double num1=maxHeap.peek(); double num2=minHeap.peek(); arr.add((num1+num2)/2); } else if(maxHeap.size() > minHeap.size()){ double num1 = maxHeap.peek(); arr.add(num1); }else{ double num1 = minHeap.peek(); arr.add(num1); } } } double[] arrs=new double[arr.size()]; for(int i=0;i<arr.size();i++){ arrs[i]=arr.get(i); } return arrs; } }
名企高频面试算法题解 文章被收录于专栏
牛客题霸 - 程序员面试高频题 - 题解