题目描述:
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
栈的特点就是后进先出(LIFO),采用数组和pop()函数就可以简单实现。这道题里主要的问题是构建栈的时候,实现获取最小值的方法。最直接的方法就是数组内元素排序取最小值。
代码如下:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
self.stack.append(x)
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[len(self.stack)-1]
def getMin(self) -> int:
return sorted(self.stack)[0]
测试结果:
这种做法测试可以通过,但是速度较慢。加入辅助列表,记录最小值,避免排序过程。代码如下:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = []
def push(self, x: int) -> None:
self.stack.append(x)
if len(self.min) == 0:
self.min.append(x)
elif self.min[-1] >= x:
self.min.append(x)
def pop(self) -> None:
x = self.stack.pop(-1)
if self.min[-1] == x:
self.min.pop(-1)
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min[-1]
测试结果:
第二种做法,速度的提升是显而易见的。
总结:
栈在python中的实现非常的容易,数组即可实现。但是涉及到实现其他栈相关方法时,还是需要考虑引入辅助对象提高处理速度。