Advertisement
sweet1cris

Untitled

Jan 9th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums: A list of integers.
  4.      * @return: the median of numbers
  5.      */
  6.     private PriorityQueue<Integer> maxHeap, minHeap;
  7.     private int numOfElements = 0;
  8.  
  9.     public int[] medianII(int[] nums) {
  10.         // write your code here
  11.         Comparator<Integer> revCmp = new Comparator<Integer>() {
  12.             @Override
  13.             public int compare(Integer left, Integer right) {
  14.                 return right.compareTo(left);
  15.             }
  16.         };
  17.         int cnt = nums.length;
  18.         maxHeap = new PriorityQueue<Integer>(cnt, revCmp);
  19.         minHeap = new PriorityQueue<Integer>(cnt);
  20.         int[] ans = new int[cnt];
  21.         for (int i = 0; i < cnt; ++i) {
  22.             addNumber(nums[i]);
  23.             ans[i] = getMedian();
  24.         }
  25.         return ans;
  26.     }
  27.     void addNumber(int value) {
  28.         maxHeap.add(value);
  29.         if (numOfElements%2 == 0) {
  30.             if (minHeap.isEmpty()) {
  31.                 numOfElements++;
  32.                 return;
  33.             }
  34.             else if (maxHeap.peek() > minHeap.peek()) {
  35.                 Integer maxHeapRoot = maxHeap.poll();
  36.                 Integer minHeapRoot = minHeap.poll();
  37.                 maxHeap.add(minHeapRoot);
  38.                 minHeap.add(maxHeapRoot);
  39.             }
  40.         }
  41.         else {
  42.             minHeap.add(maxHeap.poll());
  43.         }
  44.         numOfElements++;
  45.     }
  46.     int getMedian() {
  47.         return maxHeap.peek();
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement