Leetbook作业记录:用栈实现队列


题目概述

用栈实现队列。
题目要求用两个栈,实现队列的基本操作:push, pop, peek, empty。push的操作是在队尾添加元素,pop和peek则都需要在队首操作。
要求均摊时间在O(1), 也就是n个元素的用时控制在O(n)。


题目地址:https://leetcode-cn.com/leetbook/read/queue-stack/gvtxe/

一、解题思路

因为给出可以使用两个栈的条件,那么一个用来顺序存储元素,另一个用来逆序存储元素。

因为均摊时间要在O(1),那么逆序存储就控制在某个步骤就好了,不能瞎折腾。push这个操作天然可爱,就保持stack的顺序好啦,pop和peek是我们要关注的点。当逆序栈为空的时候,我们需要把顺序栈里的元素倒入逆序栈才能pop或者peek,这个倾倒的操作如果 pop完成了,peek就捡现成的啦,如果peek完成了,pop也是坐享其成,真是好搭档啊!

二、作业记录

1.作业代码

代码如下:

class MyQueue {

  
    Stack<Integer> in = new Stack<Integer>();
    Stack<Integer> out = new Stack<Integer>();

    /** Initialize your data structure here. */
    public MyQueue() {    
        in = new Stack();
        out = new Stack();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);        
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {

        if( !out.isEmpty()){
            return out.pop();
        }else{
            while( !in.isEmpty()){
                out.push( in.pop());
            }
            return out.pop();
        }


    }
    
    /** Get the front element. */
    public int peek() {
        if( !out.isEmpty()){
            return out.peek();
        }else{
            while( !in.isEmpty()){
                out.push( in.pop());
            }
            return out.peek();
        }       

    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

2.作业表现

表现如下:
在这里插入图片描述

好像内存消耗还有进步空间。


复杂度分析

时间复杂度:均摊时间复杂度应该是O(1),因为每次只有当pop或者peek操作时out为空时需要从in栈倾倒元素到out栈,复杂度是O(m),m是in栈的元素个数,其余时间各种操作都是O(1),均摊下来时间复杂度是O(1)。

空间复杂度:虽然需要两个栈存储元素,但是元素不会重复存储,要么在in栈,要么在out栈,所以没有占用额外的存储,空间复杂度我个人觉得是O(1)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不争之德

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值