0%

leetCode-155:Min Stack

问题描述

要求实现一个MinStack,里面包含以下函数

  • push:向栈中压入元素
  • pop:弹出栈顶元素
  • top:返回栈顶元素
  • getMin:返回当前栈中元素的最小值

要求上述每个操作都在 O(1) 的时间复杂度内完成。题目链接:**点我**

样例输入输出

输入:

1
2
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:[null,null,null,null,-3,null,0,-2]

解释:

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

问题解法

使用两个栈,一个栈用来存在每次操作的数字,另一个栈用来存储当前栈中的最小值,每次入栈操作时,都将最小值的栈顶元素和要入栈的元素进行比较,将值小的值放入最小值栈中,出栈的时候两个栈的栈顶元素都要出栈。在调用 getMin 时,直接返回最小值栈的栈顶元素即可。代码如下

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
class MinStack {
private Stack<Integer> numStack;

private Stack<Integer> minNumStack;

public MinStack() {
numStack = new Stack<>();
minNumStack = new Stack<>();
}

public void push(int val) {
numStack.push(val);
if (minNumStack.isEmpty()) {
minNumStack.push(val);
return;
}

int min = Math.min(val, minNumStack.peek());
minNumStack.push(min);
}

public void pop() {
numStack.pop();
minNumStack.pop();
}

public int top() {
return numStack.peek();
}

public int getMin() {
return minNumStack.peek();
}
}

/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/