Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Created February 18, 2014 04:28
Show Gist options
  • Select an option

  • Save rayjcwu/9064656 to your computer and use it in GitHub Desktop.

Select an option

Save rayjcwu/9064656 to your computer and use it in GitHub Desktop.
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