155. min stack 解法

155. Min Stack

Difficulty: Easy

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

Example:

1
2
3
4
5
6
7
8
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.

解法

  基本思想就是用空间换时间,入栈每个元素时都记录从该元素到栈底的所有元素的最小值,要入栈的元素对应的最小值只需取入栈之前的栈顶元素的最小值和要入栈的元素值中的最小值即可。时间复杂度O(1)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class :

def __init__(self):
"""
initialize your data structure here.
"""
self.st = []

def push(self, x: int) -> None:
if not self.st:
self.st.append((x, x))
else:
self.st.append((x, min(self.st[-1][1], x)))

def pop(self) -> None:
if self.st:
self.st.pop()

def top(self) -> int:
return self.st[-1][0]

def getMin(self) -> int:
return self.st[-1][1]