Find the Median

  • + 0 comments

    Java solution.

    public static int findMedian(List<Integer> arr) {
            PriorityQueue<Integer> minHeap = new PriorityQueue<>(Comparator.naturalOrder());
            
            PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
            
            for (int n : arr) {
                minHeap.offer(n);
                maxHeap.offer(minHeap.poll());
                
                if (maxHeap.size() > minHeap.size()) {
                    minHeap.offer(maxHeap.poll());
                }
            }
            if (minHeap.size() > maxHeap.size()) {
                return minHeap.peek();
            } else {
                long median = (minHeap.peek() + maxHeap.peek()) / 2;
                return (int) median;
            }
        }