【LeetCode 简单题】59-用队列实现栈

声明:

今天是第59道题。给定一个整数数组,判断是否存在重复元素。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

注意:

  • 你只能使用队列的基本操作-- 也就是 push to backpeek/pop from frontsize, 和 is empty 这些操作是合法的。
  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

解法1。用列表实现的,都是一些list支持的常规的操作来实现相应的功能, 耗时24 ms, 在Implement Stack using Queues的Python提交中击败了95.05%的用户,代码如下。

class MyStack(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack == []

    def push(self,x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        return self.stack.append(x)

    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        if self.stack == []:
            return None
        else:
            top = self.stack[-1]
            del self.stack[-1]
            return top

    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        if self.stack == []:
            return None
        else:  
            return self.stack[-1]

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        if self.stack == []:
            return True
        else:
            return False

解法2。用队列做,基础队列遵循先进先出的原则,建立2个队列,q1是主队列,q2是辅助队列,辅助队列主要是在进行pop和top操作时保留需要的原队列的元素。耗时24 ms, 在Implement Stack using Queues的Python提交中击败了95.05%的用户,代码如下。

  • 队列的push就是:put()
  • 队列的pop就是:get()
  • 队列的长度len就是:qsize()
class MyStack(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.q1 = Queue()
        self.q2 = Queue()

    def push(self,x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: void
        """
        self.q1.put(x)


    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        while self.q1.qsize() > 1:
            self.q2.put(self.q1.get())
        if self.q1.qsize() == 1:
            res = self.q1.get()
        tmp = self.q2     # 保存q2的值也就是保存q1的值,但不含有最后进来的元素
        self.q2 = self.q1    # 清空q2
        self.q1 = tmp    # 恢复q1
        return res    # 返回最后进来的元素
        


    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        while self.q1.qsize() >1:
            self.q2.put(self.q1.get())
        if self.q1.qsize() == 1:
            res = self.q1.get()
            self.q2.put(res) # 因为top并不删除元素,所以最后1个进来的元素要put回去,用q2来保存
        tmp = self.q2
        self.q2 = self.q1
        self.q1 = tmp
        return res

    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        # 个人认为这里应该写成:return self.q1.qsize() == 0
        return not bool(self.q1.qsize()+self.q2.qsize())

结尾

解法1:https://blog.csdn.net/qq_34364995/article/details/80640470

解法2:LeetCode

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83420567