题目描述
输入样例
17
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用于求中值
1.入栈。对于栈,直接push。然后找到其在vector中的对应位置,保持vetcor单调递增
2.出栈。对于栈,直接pop。然后找到其在vector中的对应位置,将其删除,保持vetcor单调递增
3.求中值。按照题目要求,返回vector对应下标的值即可
注意
①lower_bound函数,寻找一个数的左边界,即第一个>=它的值
②vector 中insert和erase能够插入和删除指定位置
AC代码
#include <bits/stdc++.h>
using namespace std;
stack<int> stk; //用于删除和返回栈顶元素
vector<int> temp; //用于求中值
string s;
int main()
{
int n;
cin >> n;
while(n --)
{
cin >> s;
if(s == "Pop")
{
if(!stk.size()) cout << "Invalid" << endl;
else
{
int num = stk.top();
stk.pop();
cout << num << endl;
temp.erase(lower_bound(temp.begin(), temp.end(), num));
}
}
else if(s == "Push")
{
int x;
cin >> x;
stk.push(x);
temp.insert(lower_bound(temp.begin(), temp.end(), x), x);
}
else
{
if(!stk.size()) cout << "Invalid" << endl;
else
{
int len = temp.size();
if(len % 2) cout << temp[(len + 1) / 2 - 1] << endl;
else cout << temp[len / 2 - 1] << endl;
}
}
}
return 0;
}
欢迎大家批评指正!!!