Follow these steps: addnewnumer (INT num) and getmedian ()
Maintain two priority queue: maxheap and minheap.
Maxheap stores elements smaller than the median, and minheap stores elements greater than the median. Ensure that the number of elements in the two heap is equal or Max is greater than min.
import java.util.Comparator;import java.util.PriorityQueue;public class Median { PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(10, new Comparator<Integer>() { public int compare(Integer x, Integer y) { return y.compareTo(x); } }); PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(); public void addNewNumber(int num) { if (maxHeap.size() == minHeap.size()) { if (!minHeap.isEmpty() && num > minHeap.peek()) { maxHeap.add(minHeap.remove()); minHeap.add(num); } else { maxHeap.add(num); } } else { if (num < maxHeap.peek()) { minHeap.add(maxHeap.remove()); maxHeap.add(num); } else { minHeap.offer(num); } } } public double getMedian() { if (maxHeap.isEmpty()) return 0; if (maxHeap.size() == minHeap.size()) return (double) (minHeap.peek() + maxHeap.peek()) / 2; else return maxHeap.peek(); } public static void main(String[] args) { Median m = new Median(); m.addNewNumber(1); System.out.println(m.getMedian()); m.addNewNumber(3); System.out.println(m.getMedian()); m.addNewNumber(4); System.out.println(m.getMedian()); m.addNewNumber(5); System.out.println(m.getMedian()); m.addNewNumber(2); System.out.println(m.getMedian()); }}
18.9 generate random numbers and input an insertion method. Compile a program to efficiently Insert the maintenance median of elements.