输入样例:
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
输出样例:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
题目意思是找中位数,当然和中位数还有点不一样。
首先我们必定要有个栈,但是我们不能光有一个栈。这样不能找已有元素的中值。所以我设置了一个vector,理由如下
vector支持随机访问,这是其他stl容器难实现的一点。比如set可以查询中值,但是会去重,虽然有其它的策略可以实现不去重,但是不能随机防问还是很致命的。
我刚知道vector可以插入元素,这是我用他的另一个原因。但是其实他的时间复杂度还不是很优秀的,毕竟是个数组,插入的话要移动后边的元素。跟每插入一个就sort一遍的时间复杂度一样,可能常数小一点。
写一篇博客记录一下vector的用法
#include <bits/stdc++.h>
const int N = 100100;
using namespace std;
int n, f;
int tot;
int a[N];
vector<int> v;
string s;
int main() {
cin >> n;
while (n--) {
cin >> s;
if (s == "Pop") {
if (tot == 0)
cout << "Invalid" << endl;
else {
int f = a[tot--];
cout << f << endl;
auto it = lower_bound(v.begin(), v.end(), f);
v.erase(it);
}
} else if (s == "Push") {
cin >> f;
a[++tot] = f;
auto it = lower_bound(v.begin(), v.end(), f);
v.insert(it, f);
} else {
if (tot == 0)
cout << "Invalid" << endl;
else {
if (tot % 2 == 0)
cout << v[tot / 2 - 1] << endl;
else
cout << v[(tot + 1) / 2 - 1] << endl;
}
}
}
return 0;
}