中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。 double findMedian() - 返回目前所有元素的中位数。
解题思路
这一题可以取中值可以判断2种情况
- 如果数组长度为奇数,则直接取中值 (length - 1) / 2
- 如果数组长度为偶数,则取中心位置的两个值相加除于2 ((length / 2) + (len / 2 - 1)) / 2
代码
/**
* initialize your data structure here.
*/
var MedianFinder = function() {
this.item = [];
};
/**
* @param {number} num
* @return {void}
*/
MedianFinder.prototype.addNum = function(num) {
this.item.push(num);
};
/**
* @return {number}
*/
MedianFinder.prototype.findMedian = function() {
(this.item).sort((a, b) => a - b);
// 判断总数量是否为偶数
if (this.item.length % 2) {
return this.item[(this.item.length - 1) / 2];
} else {
return (this.item[this.item.length / 2] + this.item[this.item.length / 2 - 1]) / 2;
}
};