python - 相同的逻辑适用于 c++,但不适用于 python 中的最大堆栈,我的代码中是否缺少某些东西

标签 python c++ stack max python-3.6

我在 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 中使用 queue 模块的 LIFO,但直到现在我在使用列表作为堆栈之前没有遇到任何问题。

它们对所有测试用例都应该相同。

最佳答案

你只有 1 个 python“堆栈”:

stack1 = stack2 = []     # two names that point to the same list

print(id(stack1))
print(id(stack2))

# vs

stack1 = []              # points to one list
stack2 = []              # points to another list

print(id(stack1))
print(id(stack2))

输出:

139948335562312
139948335562312

# vs

139948335067208
139948335562696

关于python - 相同的逻辑适用于 c++,但不适用于 python 中的最大堆栈,我的代码中是否缺少某些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55314425/

相关文章:

python - 在 virtualenv 中安装 mysqlclient 时出错

python - 从统计文件中构建计数字典

c++ - 使用 cv::HoughCircles() 检测邻近的许多小圆圈

c++ - 如何从变量中删除特定字符串

c++ - 编译错误。如何使用 lex/yacc 解析变量名?

c - 将寄存器转储到堆栈中以进行保守的堆栈扫描

python - scapy - srp 没有将我的数据包发送到正确的网络接口(interface)

python - 在 python 中绘制图表 - LineCollection

linux - 确定线程的堆栈大小和位置

c++ - pop如何使用链表在堆栈中工作?