• 0232-leetcode算法实现-用栈实现队列-implement-queue-using-stacks-python&golang实现


    请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

    实现 MyQueue 类:

    void push(int x) 将元素 x 推到队列的末尾
    int pop() 从队列的开头移除并返回元素
    int peek() 返回队列开头的元素
    boolean empty() 如果队列为空,返回 true ;否则,返回 false

    说明:

    你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

    进阶:

    你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

    示例:

    输入:
    ["MyQueue", "push", "push", "peek", "pop", "empty"]
    [[], [1], [2], [], [], []]
    输出:
    [null, null, null, 1, 1, false]

    解释:
    MyQueue myQueue = new MyQueue();
    myQueue.push(1); // queue is: [1]
    myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
    myQueue.peek(); // return 1
    myQueue.pop(); // return 1, queue is [2]
    myQueue.empty(); // return false

    提示:

    1 <= x <= 9
    最多调用 100 次 push、pop、peek 和 empty
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/implement-queue-using-stacks

    思路:
    将一个栈当作输入栈,用于压入 push 传入的数据;另一个栈当作输出栈,用于pop 和 peek 操作。
    每次 pop 或 peek 时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。
    
    复杂度分析:
    时间复杂度:push 和 empty 为 O(1),pop 和 peek 为均摊 O(1)。对于每个元素,至多入栈和出栈各两次,故均摊复杂度为 O(1)。
    空间复杂度:O(n)。其中 n 是操作总数。对于有 n 次push 操作的情况,队列中会有 n 个元素,故空间复杂度为 O(n)。
    
    
    链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/yong-zhan-shi-xian-dui-lie-by-leetcode-s-xnb6/
    
    

    python

    # 0232.栈实现队列
    """
    
    """
    class MyQueue:
        def __init__(self):
            # in -> push, out -> pop
            self.stack_in = []
            self.stack_out = []
    
        def push(self, x: int):
            # 有新元素进来,往in push
            self.stack_in.append(x)
    
        def pop(self) -> int:
            # 空栈,弹空,否则out非空pop,或者将in元素全部入栈到out,最后out pop
            if self.empty():
                return None
            if self.stack_out:
                return self.stack_out.pop()
            else:
                for i in range(len(self.stack_in)):
                    self.stack_out.append(self.stack_in.pop())
                return self.stack_out.pop()
    
        def peek(self) -> int:
            # 从出栈pop,然后append进出栈
            ans = self.pop()
            self.stack_out.append(ans)
            return ans
    
        def empty(self) -> bool:
            # 进栈与出栈都为空
            return not (self.stack_in or self.stack_out)
    

    golang

    package main
    
    type MyQueue struct {
    	inStack  []int // push, 作为对外入栈
    	outStack []int // pop, 作为对外出栈
    }
    
    // initialize data struct
    func Constructor() MyQueue {
    	return MyQueue{
    		inStack:  make([]int, 0), // push
    		outStack: make([]int, 0), // pop
    	}
    }
    
    // push,直接压入instack
    func (this *MyQueue) Push(x int) {
    	this.inStack = append(this.inStack, x)
    }
    
    // instack -> outStack
    func (this *MyQueue) in2out() {
    	for len(this.inStack) > 0 {
    		this.outStack = append(this.outStack, this.inStack[len(this.inStack)-1])
    		this.inStack = this.inStack[:len(this.inStack)-1]
    	}
    }
    
    // pop,instack中的所有元素移入oustack中,get出栈的最顶的元素,outstack重新获取切片
    func (this *MyQueue) Pop() int {
    	if len(this.outStack) == 0 {
    		this.in2out()
    	}
    	val := this.outStack[len(this.outStack)-1]
    	this.outStack = this.outStack[:len(this.outStack)-1]
    	return val
    
    }
    
    // peek, instack中的所有元素移入outstack中,get出栈的最顶的元素
    func (this *MyQueue) Peek() int {
    	for len(this.outStack) == 0 {
    		this.in2out()
    	}
    	return this.outStack[len(this.outStack)-1]
    }
    
    // empty, 进栈和出栈的栈都没有元素才为空
    func (this *MyQueue) Empty() bool {
    	return len(this.inStack) == 0 && len(this.outStack) == 0
    }
    
    
  • 相关阅读:
    mysql主从延迟判断,监控和问题处理
    oracle备份
    oracle的查询命令
    Appcan 自定义数字加减控件
    PowerDesigner16.5 有用地址
    git远程仓库关联(码云)
    leetcode27.移除元素(双指针法)
    leetcode26.删除排序数组中的重复项(双指针法,顺序表删除)
    leetcode21.合并两个有序链表(链表使用,递归算法)
    leetcode20.有效的括号(hashmap使用,键值匹配)
  • 原文地址:https://www.cnblogs.com/davis12/p/15522627.html
Copyright © 2020-2023  润新知