问题
M个数字的中位数定义为:
1)如果M是奇数,则在将它们排序后中间的数字;
2)如果M是偶数,则是排序后中间2个数字的平均数。
一开始,您有一个空数字列表。然后您可以向列表中添加或删除一些数字。对于每个添加或删除操作,请输出列表中的中位数。
示例:对于一个集合m = 5的数字{9,2,8,4,1},中位数是排序集{1,2,4,8,9}中的第三个数字,即4。同样对于m = 4的集合{5,2,10,4},中位数是排序集{2,4,5,10}中第二个和第三个元素的平均值,即(4+5)/2 = 4.5。
我的方法 我认为这个问题可以这样解决... 思路是使用先前的中位数值和指针来找到新的中位数值,而不是在每个添加或删除操作时重新计算。1)使用 multiset(多重集合),它们始终按顺序保留元素并允许重复。换句话说,以某种方式维护排序的列表。
2)如果操作是添加
2.1) Insert this element into set and then calculate the median
2.2) if the size of set is 1 then first element will be the median
2.3) if the size of set is even, then
if new element is larger then prev median, new median will be avg of prev median
and the next element in set.
else new median will be avg of prev median and previous of prev element in the set.
2.4) if the size is odd, then
if new element is larger then prev median
if also less then 2nd element of prev median ( 2nd element used to calculate avg
of prev median) then this new element to be added will be new median
else median will be 2nd element use to calculate the avg during last iteration prev
median.
else
new median will be previous of prev median element in the set
3) 如果操作是删除
3.1) First calculate the new median
3.2) If the size of set is 0 can't remove
3.3) If the size is 1 if the first element is the element to be removed, remove it else can't remove.
3.4) If the size of set is even, then
if the element to be deleted is greater than or equal to 2nd element of prev median, then
1st element of prev median will be new median
else 2nd element of prev median will be the new median
3.5) If the size of set is odd, then
if the element to be deleted is the prev median then find the avg of its prev and next element.
else if the element to be deleted is greater then prev median, new median will be avg of prev median and previous to prev median
else median will be avg of prev median and next element to prev median.
3.6) Remove the element.
以下是可用代码...http://justprogrammng.blogspot.com/2012/06/interviewstreet-median-challenge.html。您对此方法有何看法?