Numbers keep coming, return the median of numbers at every time a new number added.
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, ifA=[1,2,3]
, median is 2
. If A=[1,19]
, median is 1
.
Example
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]
.
分析:
使用两个heap,一个min heap(root的值最小) and max heap (root的值最大)。保持两个heap的size差别最大为1,并且,min heap永远不会不max heap的size大。
1 public class Solution { 2 /** 3 * @param nums: A list of integers. 4 * @return: the median of numbers 5 */ 6 public int[] medianII(int[] nums) { 7 if (nums == null || nums.length == 0) 8 return null; 9 10 int[] med = new int[nums.length]; 11 12 PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); 13 PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11, new Comparator<Integer>() { 14 public int compare(Integer x, Integer y) { 15 return y - x; 16 } 17 }); 18 19 med[0] = nums[0]; 20 maxHeap.offer(nums[0]); 21 22 for (int i = 1; i < nums.length; i++) { 23 if (nums[i] < maxHeap.peek()) { 24 maxHeap.offer(nums[i]); 25 } else { 26 minHeap.offer(nums[i]); 27 } 28 29 if (maxHeap.size() > minHeap.size() + 1) { 30 minHeap.offer(maxHeap.poll()); 31 } else if (maxHeap.size() < minHeap.size()) { 32 maxHeap.offer(minHeap.poll()); 33 } 34 med[i] = maxHeap.peek(); 35 } 36 return med; 37 } 38 }
时间: 2024-10-08 10:34:05