问题 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) 使用始终保持元素有序并允许重复的多重集。换句话说,以某种方式维护排序列表。
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。您对这种方法有何看法?