fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. { Integer[] arr= {10,70,4,15,20,12,8,17};
  12. PriorityQueue<Integer>maxheap = new PriorityQueue<>(10, Collections.reverseOrder());
  13. PriorityQueue<Integer>minheap = new PriorityQueue<>(10);
  14. Integer median = -9999;
  15. for (Integer a: arr) {
  16. if (a >= median) {
  17. minheap.add(a);
  18. if (minheap.size() - maxheap.size() >= 2)
  19. maxheap.add(minheap.poll());
  20. }
  21. else {
  22. maxheap.add(a);
  23. if (maxheap.size() - minheap.size() >= 2)
  24. minheap.add(maxheap.poll());
  25. }
  26. Integer diff = maxheap.size() - minheap.size();
  27. if (diff == 1)
  28. median = maxheap.peek();
  29. else if (diff == -1)
  30. median = minheap.peek();
  31. else
  32. median = Math.min(minheap.peek(), maxheap.peek());
  33. System.out.println(median);
  34. }
  35. }
  36.  
  37. }
Success #stdin #stdout 0.06s 32608KB
stdin
Standard input is empty
stdout
10
10
10
10
15
12
12
12