LeetCode上有两道关于Stack的题目:
其中MinStack有个变体题目是MinQueue,简单地来说就是要实现Queue的常用操作,并使获取Queue中的最小值操作所需的时间复杂度为常数。
由于直接套MinStack的Solution在MinQueue上是行不通的,因此可以先实现MinStack,再用MinStack实现Queue。
MinStack
Problem Description
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- getMin() – Retrieve the minimum element in the stack.
Solution
解法有两种,但是核心思想都是利用空间换时间。
Solution A
在原有的栈的基础上,再维护一个存放最小值索引的栈。
For Example:
Talk is cheap, show code.
class MinStack(object):
def __init__(self):
self.index_stack = []
self.data_stack = []
def pop(self):
"""
判断出栈值是否为最小索引栈的top值,如果是,最小索引栈也执行pop操作
:return:
"""
o = self.data_stack[-1]
if o == self.data_stack[self.index_stack[-1]]:
self.index_stack.pop()