class MedianFinder {
private:
vector<int> nums;
public:
// Adds a number into the data structure.
void addNum(int num) {
int s = 0, e = nums.size() - 1;
int m;
while (s <= e) {
m = s + (e - s) / 2;
if (nums[m] < num) s = m + 1;
else if (nums[m] > num) e = m - 1;
else {
s = m + 1;
break;
}
}
nums.insert(nums.begin() + s, num);
}
// Returns the median of current data stream
double findMedian() {
int n = nums.size();
if (n == 0) return 0;
if (n % 2) {
return nums[n/2];
} else {
return ((double)nums[n/2 - 1] + (double)nums[n/2]) / 2;
}
}
};
// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf;
// mf.addNum(1);
// mf.findMedian();
Find Median from Data Stream
最新推荐文章于 2023-01-03 17:14:07 发布