我在python和c ++中编写了相同的逻辑,以使用两个堆栈在O(1)时间中返回堆栈中的最大元素。但是当我在hackerrank上提交它时,它显示了python错误的答案,但接受了c ++。我在python中缺少什么吗?
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,q,x;
stack<int>s1,s2;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>q;//here q is a type of query
switch(q)
{
//push in stack
case 1:
cin>>x;
if (s1.empty())
{
s2.push(x);
}
else
{
if (x >= s2.top())
{
s2.push(x);
}
}
s1.push(x);
break;
//pop from stack
case 2:
if(!s1.empty())
{
if(s1.top()==s2.top())
{
s2.pop();
}
s1.pop();
}
break;
//getMax from stack
case 3:
if(!s2.empty())
cout<<s2.top()<<endl;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
stack1 = …Run Code Online (Sandbox Code Playgroud)