问题描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
思路分析:
构建一个辅助栈helper来辅助解决问题;
向栈stack压入元素的时候,如果辅助栈没有元素或者压入的值小于辅助栈顶的值,就将其同时压入栈stack和辅助栈helper;
如果压入的值大于或者等于辅助栈顶,则辅助栈再次压入辅助栈栈顶的指,这样可以保证辅助栈栈顶始终是最小值;
进行pop操作的时候栈stack和辅助栈helper同时进行pop操作,要保持同步,这样同样也是可以保证辅助栈栈顶始终是最小值;
此时返回辅助栈栈顶就是可以得到最小值。
python实现代码如下:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.helper = [] #构建辅助栈
def push(self, node):
# write code here
min = self.min() #取出辅助栈最小元素
if not min or node < min:
self.helper.append(node)
else:
self.helper.append(min)
self.stack.append(node)
def pop(self):
# write code here
if self.stack:
self.helper.pop()
return self.stack.pop()
def top(self):
# write code here
if self.stack:
return self.stack[-1]
def min(self):
# write code here
if self.helper:
return self.helper[-1]