加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

相同的逻辑适用于c但不能在python中最大化堆栈,我的代码中是否存

发布时间:2020-12-16 09:23:06 所属栏目:百科 来源:网络整理
导读:我在 python和c中编写了相同的逻辑,使用两个堆栈在O(1)时间内返回堆栈中的最大元素.但是当我在hackerrank上提交它时,它显示错误的python答案但接受c. 我在python中遗漏了什么. #include bits/stdc++.husing namespace std;int main() { int n,q,x; stackints
我在 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,但到目前为止我还没有遇到任何使用列表作为堆栈的问题.

它们都应该适用于所有测试用例.

解决方法

你只有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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读