题目描述
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4]
, the median is 3
[2,3]
, the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
- void addNum(int num) - Add a integer number from the data stream to the data structure.
- double findMedian() - Return the median of all elements so far.
题目大意
要求完成两个操作:插入数字,找到插入数字的中位数(若插入了偶数个数字,则中位数为中间两个数字的平均值)。
示例
E1
解题思路
在每次插入的时候二分查找到应该插入的位置,使得所有数字保持有序。最后查找中位数的时候只需要输出中间的数字即可。
复杂度分析
时间复杂度:O(N*log(N))
空间复杂度:O(N)
代码
class MedianFinder { public: /** initialize your data structure here. */ MedianFinder() { } void addNum(int num) { if(nums.empty()) nums.push_back(num); else { // 插入数字,使得所有数字有序排列 nums.insert(lower_bound(nums.begin(), nums.end(), num), num); } } double findMedian() { int n = nums.size(); // 访问中间的位置,需判断数字总数是否为偶数 return n & 1 ? nums[n / 2] : (nums[n / 2 - 1] + nums[n / 2]) * 0.5; } private: vector<int> nums; }; /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */