定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
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]
Java版代码,leetcode地址:
1 class MinStack { 2 3 Stack<Integer> normalStack; 4 Stack<Integer> minStack; 5 6 /** initialize your data structure here. */ 7 public MinStack() { 8 normalStack = new Stack<Integer>(); 9 minStack = new Stack<Integer>(); 10 } 11 12 public void push(int x) { 13 normalStack.add(x); 14 if (minStack.isEmpty() || minStack.peek() >= x) { 15 minStack.add(x); 16 } 17 } 18 19 public void pop() { 20 int x = normalStack.pop(); 21 if (x == minStack.peek()) { 22 minStack.pop(); 23 } 24 } 25 26 public int top() { 27 return normalStack.peek(); 28 } 29 30 public int min() { 31 return minStack.peek(); 32 } 33 }