-
Notifications
You must be signed in to change notification settings - Fork 1
/
Offer30.java
42 lines (36 loc) · 879 Bytes
/
Offer30.java
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
package lcof;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Offer30. 包含 min 函数的栈
* 思路:用一个辅助栈,专门存放最小值
* @author LBW
*/
public class Offer30 {
private Deque<Integer> stack; // 存放数字
private Deque<Integer> minStack; // 存放最小值
/** initialize your data structure here. */
public Offer30() {
stack = new ArrayDeque<>();
minStack = new ArrayDeque<>();
}
public void push(int x) {
stack.push(x);
if (minStack.isEmpty()) {
minStack.push(x);
}
else {
minStack.push(Math.min(minStack.peek(), x));
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}