【发布时间】:2019-08-14 07:32:55
【问题描述】:
我在 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;
}
stack1 = stack2 = []
N = int(input())
for i in range(N):
a = list(map(int,input().rstrip().split()))
if a[0]==1:
if stack1 == []:
stack2.append(a[1])
elif a[1]>=stack2[-1]:
stack2.append(a[1])
stack1.append(a[1])
elif a[0]==2:
if stack1 != []:
if stack1[-1] == stack2[-1]:
stack2.pop()
stack1.pop()
elif a[0] == 3:
if stack2 != []:
print(stack2[-1])
在我看来是一样的。
我在其他在线编译器上尝试了一些我自己的测试用例,它们对两者的工作方式相同。 我是否应该在 python 中使用队列模块中的 LIFO,但到目前为止我在使用列表作为堆栈之前还没有遇到任何问题。
它们对于所有测试用例都应该同样工作。
【问题讨论】:
标签: python c++ stack max python-3.6