[LeetCode]题解(python):155-Min Stack

时间:2023-03-09 20:59:31
[LeetCode]题解(python):155-Min Stack

题目来源:

  https://leetcode.com/problems/min-stack/


题意分析:

  实现一个小的栈,包括初始化,push,pop,top,和getMin。


题目思路:

  思路是用两个数组来处理。


代码(python):

 class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1 = []
self.stack2 = [] def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x) def pop(self):
"""
:rtype: nothing
"""
tmp = self.stack1.pop()
if tmp == self.stack2[-1]:
self.stack2.pop() def top(self):
"""
:rtype: int
"""
return self.stack1[-1] def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]