剑指offer 20 包含min函数的栈

it2022-05-05  185

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

# -*- coding:utf-8 -*- # 思路:用一个栈stack保存数据,用另外一个栈min_stack保存依次入栈最小的数 # 比如,stack中依次入栈,5, 4, 3, 8, 10, 11, 12, 1 # 则min_stack依次入栈,5, 4, 3,no, no, no, no, 1 # no代表此次不如栈 # 每次入栈的时候,如果入栈的元素比min中的栈顶元素小或等于则入栈,否则不如栈。 # -*- coding:utf-8 -*- class Solution: def __init__(self): self.stack = [] self.min_stack = [] def push(self, node): # write code here self.stack.append(node) if not self.min_stack or node <= self.min_stack[-1]: self.min_stack.append(node) def pop(self): # write code here if self.stack[-1] == self.min_stack[-1]: self.min_stack.pop() self.stack.pop() def top(self): # write code here return self.stack[-1] def min(self): # write code here return self.min_stack[-1]

 


最新回复(0)