小编UKD*_*D28的帖子

相同的逻辑适用于c ++,但不适用于python以最大程度地增加堆栈,代码中是否缺少某些内容

我在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)

c++ python stack max python-3.6

3
推荐指数
1
解决办法
42
查看次数

标签 统计

c++ ×1

max ×1

python ×1

python-3.6 ×1

stack ×1