定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
基本思想:假设当前栈为A,每次对栈A进行push操作的时候,将栈A中最小的元素push进辅助栈B中。
# -*- coding:utf-8 -*-
class Stack:
def __init__(self):
self.array = []
def push(self, node):
self.array.append(node)
def pop(self):
if len(self.array) > 0:
return self.array.pop()
def top(self):
if len(self.array) > 0:
return self.array[-1]
class Solution:
def __init__(self):
self.s_data = Stack()
self.s_min = Stack()
def push(self, node):
# write code here
self.s_data.push(node)
if len(self.s_min.array) == 0 or node < self.s_min.top():
self.s_min.push(node)
else:
self.s_min.push(self.s_min.top())
def pop(self):
# write code here
s1 = self.s_data.pop()
s2 = self.s_min.pop()
return s1
def top(self):
# write code here
return self.s_data.top()
def min(self):
# write code here
return self.s_min.top()
还有一种思路是,当前元素如果不小于栈A中最小的元素,则辅助栈B不入栈。这种思路下栈A出栈的时候,需要通过判断栈B栈顶元素是否跟栈A栈顶元素相同来决定栈B是否需要出栈。
本文介绍了一种在栈数据结构中高效获取最小元素的方法。通过维护一个辅助栈,该方法能够在进行常规栈操作的同时,始终保持对栈内最小值的跟踪。
1445

被折叠的 条评论
为什么被折叠?



