155. min stack

Description

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:


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.

题意:

自己实现一个栈,除了推、弹、查看栈顶以外还要求常数时间找到栈中最小值。

Solution

基本思路是使用 list 结构,自带 push(append)与 pop 方法。top 只需要返回最后一个元素。
对于最小值,最单纯的思路是用自带方法返回 min(list),但是时间复杂度不允许。
因此维护一个最小值 stack,在每次 push 的时顺便在最小值 stack 中 push 当前最小值(包括输入值),每次 pop 时最小值栈也随之 pop。需要获取最小值时只需要获取最小值 stack 的最后一个元素即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class (object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_q = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if self.min_q == []:
self.min_q.append(x)
else:
self.min_q.append(min(x, self.min_q[-1]))
def pop(self):
"""
:rtype: void
"""
self.stack.pop()
self.min_q.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min_q[-1]
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()