作者bleed1979 (十三)
站内Prob_Solve
标题Re: online algorithm 找中位数
时间Sat Aug 18 05:10:41 2012
※ 引述《sorryChen (陈扬和)》之铭言:
: ※ [本文转录自 Programming 看板 #1GBUF2_m ]
: 作者: sorryChen (陈扬和) 看板: Programming
: 标题: online algorithm 找中位数
: 时间: Fri Aug 17 14:25:04 2012
: 这是个面试问题..但我也不知道解答
: 给定一个一直会产生的数列..要如何最有效率的找到中位数
: 如果是要求平均只要constant time 和 space, 中位数就得要所有数都存了
: (因为任何过去出现的数都有可能在新产生几个数列後变成中位数)
: 如果固定n个数, 需要O(n)的时间和空间可以找到第k大的数(任意k)
: (selection), 但如果这个数列一直在产生呢?
: 有没有data structure 可以在n个数後新加m个数,而能在O(m)找到中位数?
: O(mlogn)倒是应该可以(不太确定)
: 若有个blance binary search tree, 并且计有每个子树下有多少个数,
: 中位数应该离root不远, 可能可以在有这样的数中constant time找到
: (对吗?) 新插入m个数也只要mlogn
: 实际问题若资料有特殊的分布也许也可以把数分堆
: 不知道版上有没有大师可以指导解惑
case 1:
n0, n1, n2, n3, n4, n5, n6, n7, n8, n9
=> priority_queue1 priority_queue2
n0, n1, n2, n3, n4 n5, n6, n7, n8, n9
midian = (n4 + n5) / 2
case 2:
n0
midian = n0
case 3:
n0, n1, n2
=> priority_queue1 priority_queue2
n0, n1 n2
midian = n1
http://zerojudge.tw/ShowProblem?problemid=d713
#include <iostream>
#include <queue>
using namespace std;
struct COMPL {
bool operator()(const int& lhs, const int& rhs) {
return lhs < rhs;
}
};
struct COMPR {
bool operator()(const int& lhs, const int& rhs) {
return lhs > rhs;
}
};
int n;
priority_queue<int, vector<int>, COMPL> qLeft;
priority_queue<int, vector<int>, COMPR> qRight;
int main() {
while(cin >> n) {
qLeft.push(n);
if(qRight.empty()) {
if(qLeft.size() > qRight.size() + 1) {
int tmp = qLeft.top();
qLeft.pop();
qRight.push(tmp);
cout << (qLeft.top() + qRight.top()) / 2 << "\n";
} else {
cout << qLeft.top() << "\n";
}
} else {
if(qLeft.size() > qRight.size() + 1) {
int tmp = qLeft.top();
qLeft.pop();
qRight.push(tmp);
cout << (qLeft.top() + qRight.top()) / 2 << "\n";
} else if(qLeft.top() > qRight.top()) {
int tmp = qLeft.top();
qLeft.pop();
qRight.push(tmp);
tmp = qRight.top();
qLeft.push(tmp);
qRight.pop();
cout << qLeft.top() << "\n";
} else {
cout << qLeft.top() << "\n";
}
}
}
return 0;
}
done.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.32.177.97
※ 编辑: bleed1979 来自: 114.32.177.97 (08/18 05:11)
1F:推 sorryChen:大神太强了..这样说起来需要O(mlogn)在n个+m个数,应该吧 08/18 12:13
2F:→ singlovesong:只用一个平衡树应该也可以达到? 08/18 15:18
3F:推 eieio:我拿去问同事结果被秒杀,还问我怎麽会没看过这题 orz 08/19 00:43