【题目】定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
【思路】对栈使用min方法,需要把最小的上面的栈的内容都拿出来,时间复杂度是O(n),但题目要求时间复杂度是O(1),所以我们通过牺牲空间换取时间,即建立一个辅助栈,辅助栈里压入的数,从大到小,若后面压入的数比前面的大,则该位置仍存储前一个位置的数。
例如辅助栈现在是9,8,7,3,现在来了一个4,比较之后,第五个位置仍存储3,而不是4,即9,8,7,3,3。
注意,当栈执行pop()时,辅助栈也要进行pop(),.
【代码实现】
class Solution:
def __init__(self):
self.stack = []
self.minValue = []
def push(self, node):
self.stack.append(node)
if self.minValue:
if self.minValue[-1] > node:
self.minValue.append(node)
else:
self.minValue.append(self.minValue[-1])
else:
self.minValue.append(node)
# write code here
def pop(self):
if self.stack == []:
return None
self.minValue.pop()
return self.stack.pop()
# write code here
def top(self):
if self.stack == []:
return None
return self.stack[-1]
# write code here
def min(self):
if self.stack == []:
return None
return self.minValue[-1]
当栈压入数据时,和辅助栈最后一个比较后,若比它大,也可以选择不存到列表中,此时在pop时就要注意,栈移除的数和辅助栈的最后一个相等时,辅助栈才执行pop,否则不执行。
【修改】
class Solution:
def __init__(self):
self.stack = []
self.minValue = []
def push(self, node):
self.stack.append(node)
if self.minValue:
if self.minValue[-1] > node:
self.minValue.append(node)
else:
self.minValue.append(node)
# write code here
def pop(self):
if self.stack == []:
return None
if self.stack[-1] == self.minValue[-1]:
self.minValue.pop()
return self.stack.pop()
# write code here
def top(self):
if self.stack == []:
return None
return self.stack[-1]
# write code here
def min(self):
if self.stack == []:
return None
return self.minValue[-1]