public class MinStack { Stack<int> S = new Stack<int>(); /** initialize your data structure here. */ int min = int.MaxValue; public MinStack() { } public void Push(int x) { if (S.Count > 0) { if (x < min) { min = x; } } else { min = x; } S.Push(x); } public void Pop() { if (S.Count > 0) { var top = S.Pop(); if (top == min && S.Count > 0) { min = S.Min(); } } } public int Top() { return S.Peek(); } public int GetMin() { return min; } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.Push(x); * obj.Pop(); * int param_3 = obj.Top(); * int param_4 = obj.GetMin(); */
https://leetcode.com/problems/min-stack/#/description
补充一个python的实现:
1 class MinStack: 2 def __init__(self): 3 self.stack = [] 4 self.min_stack = [] 5 6 def push(self, x: int) -> None: 7 self.stack.append(x) 8 if len(self.min_stack) == 0 or x <= self.min_stack[-1]: 9 self.min_stack.append(x) 10 11 def pop(self) -> None: 12 x = self.stack.pop() 13 if x == self.min_stack[-1]: 14 self.min_stack.pop() 15 16 def top(self) -> int: 17 return self.stack[-1] 18 19 def getMin(self) -> int: 20 return self.min_stack[-1]