Approach
I waw originally thinking that we can insert the number with binary search (or lower_bound), and find median with directly taking the number from index for the vector. This strategy can pass the porlbme, but this is actually an O(N) solution since vector insert can be O(n).
I then find out that we can maintain a minheap and maxheap with O(lgN) insertion time, and we only need to rebalance two heaps when their size is different by more than 2.
Code-1: Binary Search + O(N) insert
class MedianFinder {
public:
vector<int> nums;
MedianFinder() {
}
void addNum(int num) {
auto it = lower_bound(nums.begin(), nums.end(), num);
nums.insert(it, num);
}
double findMedian() {
int n = nums.size();
if(n % 2 == 1) {
return double(nums[n/2]);
} else {
return double(nums[n/2]+nums[n/2-1])/2;
}
}
};
Code-2: maxheap and minheap with O(lgN) insert
class MedianFinder {
public:
priority_queue<int> lo; // maxHeap
priority_queue<int, vector<int>, greater<int>> hi; // minHeap
MedianFinder() {
}
void addNum(int num) {
if(lo.empty()) {
lo.push(num);
} else {
int low = lo.top();
if(num >= low) {
hi.push(num);
} else {
lo.push(num);
}
}
if(lo.size()+1 < hi.size()) {
lo.push(hi.top());
hi.pop();
}
if(hi.size()+1 < lo.size()) {
hi.push(lo.top());
lo.pop();
}
}
double findMedian() {
int n = lo.size() + hi.size();
if(n % 2 == 1) {
n /= 2;
if(n == lo.size()-1) return double(lo.top());
else return double(hi.top());
} else {
return double(hi.top()+lo.top())/2;
}
}
};