/** initialize your data structure here. */ MedianFinder() { } voidaddNum(int num){ min_heap.push(num); if (min_heap.size() > max_heap.size() + 1) { max_heap.push(min_heap.top()); min_heap.pop(); } if (max_heap.size() && min_heap.top() < max_heap.top()) { int minv = min_heap.top(), maxv = max_heap.top(); min_heap.push(maxv), max_heap.push(minv); min_heap.pop(), max_heap.pop(); } } doublefindMedian(){ if ((min_heap.size() + max_heap.size()) & 1) return min_heap.top(); return (min_heap.top() + max_heap.top()) / 2.0; } };
/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */