Created
February 18, 2014 04:28
-
-
Save rayjcwu/9064656 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Median { | |
| MaxHeap maxHeap; | |
| MinHeap minHeap; | |
| // maintain invariant size of maxHeap equals to or greater than size of minHeap by 1 | |
| public void add(int x) { | |
| maxHeap.add(x); | |
| if (maxHeap.size() > minHeap.size() + 1) { | |
| minHeap.add(maxHeap.remove()); | |
| } | |
| } | |
| public int getMedian() { | |
| if ((maxHeap.size() + minHeap.size()) % 2 == 0) { | |
| return (maxHeap.peek() + minHeap.peek()) / 2; | |
| } else { | |
| return maxHeap.peek(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment