295. median data stream
The median is the middle number in an ordered list. If the list length is an even number, the median is the average of the two middle numbers.
E.g,
[2,3,4] median 3
[2,3] median is (2 + 3) / 2 = 2.5
A data structure designed to support the following two operations:
void addNum (int num) - adding data structure from the data stream to an integer.
double findMedian () - Returns the current median of all elements.
Example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
进阶:
If the data stream are all integer in the range of 0-100, how would you optimize your algorithm?
If the integer data stream, 99% are in the range of 0-100, how would you optimize your algorithm?
Thinking
A recent study Go, C ++ long time did not write.
But the problem with the C ++ STL in the big top of a small heap at the right top of the heap, but I just need to push, pop on the line, so stole a lazy.
Remember usual programming #include <queue>.
My code
class MedianFinder {
public:
MedianFinder() {
}
void addNum(int num) {
if (V.size()==0) {
V.push(num);
return;
}
if (V.size() == A.size()) {
if (num >= A.top())
V.push(num);
else {
V.push(A.top());
A.pop();
A.push(num);
}
}
else
if (num >= V.top()) {
V.push(num);
A.push(V.top());
V.pop();
}
else
A.push(num);
}
double findMedian() {
if (V.size() == A.size()) {
return (A.top() + V.top()) / 2.0;
}
else
return V.top();
}
priority_queue<int> A;
priority_queue<int, vector<int>, greater<int> > V;
};