You are viewing a single comment's thread. Return to all 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; } }
Seems like cookies are disabled on this browser, please enable them to open this website
I agree to HackerRank's Terms of Service and Privacy Policy.
Find the Median
You are viewing a single comment's thread. Return to all comments →
Java solution.