【问题标题】:Implementing Queue Using Two Stacks Time Limit Exceeded使用两个堆栈实现队列超过时间限制
【发布时间】:2021-02-05 02:57:54
【问题描述】:

https://www.hackerrank.com/challenges/queue-using-two-stacks/problem 上述问题需要使用两个堆栈实现一个队列。 所以我应该做的是回答 3 种类型的查询

  1. 入队
  2. 出队
  3. 打印顶部

我的代码如下: /*

    #include <iostream>
    #include <stack>
    using namespace std;
    
    class QueueTwoStack{
        stack<int> s1;
        stack<int> s2;
        public:
        void enqueue(int x);
        void dequeue();
        int Front();
    };
    void QueueTwoStack::enqueue(int x){ //ENQUEUE
        while(!s1.empty()){
            s2.push(s1.top());
            s1.pop();
        }
        s1.push(x);
        while(!s2.empty()){
            s1.push(s2.top());
            s2.pop();
        }
    }
    void QueueTwoStack::dequeue(){  //DEQUEUE
        if(!s1.empty())
        s1.pop();
    }
    int QueueTwoStack::Front(){ //RETURN FRONT
        return s1.top();
    }
    int main() {
        QueueTwoStack Queue;
        int q,ch,x;
        cin>>q;
        while(q--){
            cin>>ch;
            if(ch==2)
            Queue.dequeue();
            else if(ch==3)
            cout<<Queue.Front()<<endl;
            else if(ch==1){
                cin>>x;
                Queue.enqueue(x);
            }
        }
        return 0;
    }
*/

现在此代码通过了 25% 的测试用例并给出“超出时间限制”的判断。任何关于效率低下的帮助 在代码或方法中?另外我想问一下,使用类会减慢代码吗?

【问题讨论】:

  • 对于每个新元素,您将清空堆栈两次。将所有从 s1 推到 s2,然后再推回 s1。您可以使用一个堆栈来推送新的(s1)和一个堆栈弹出(s2)。如果 s2 为空,则将 s1 的所有元素压入 s2
  • 请提供minimal reproducible example 您的代码应该做什么?我无法阅读您的黑客等级链接
  • 1) 给自己一个编译器。 2) 将失败的测试用例复制到文件中。 3)重写您的代码,以便您从该文件中读取。 4) 调试你的程序。

标签: c++ class stack queue


【解决方案1】:

您正在堆栈s1 中维护一个完全排序的队列,通过将所有s1 推入s2 将元素排入队列,添加下一个元素,然后将所有s2 推回s1。这不是很理想。

让我们改为调用堆栈inout。一开始都是空的:

in:  <top>
out: <top>

排队元素只是将它们添加到in。添加1,2,3:

Add 1:
in:  1 <top>
out: <top>

Add 2:
in:  1 2 <top>
out: <top>

Add 3:
in:  1 2 3 <top>
out: <top>

出列元素只需将它们从out 中拉出 - 需要注意的是,如果out 为空,我们首先将所有in 转移到out

Dequeue:
in:  1 2 3 <top>
out: <top>            <- empty! Transfer

in:  <top>
out: 3 2 1 <top>

Out no longer empty, pop 1:

in:  <top>
out: 3 2 <top>

这样做可以确保每个元素只被触摸三次:第一次添加到in,第二次从in 转移到out,第三次从out 弹出。

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2018-06-14
    • 2014-04-21
    • 2010-09-09
    • 2014-12-23
    • 1970-01-01
    • 2021-10-06
    • 2021-07-08
    • 2017-12-21
    相关资源
    最近更新 更多