-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinStack.java
69 lines (52 loc) · 1.44 KB
/
MinStack.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package algorithms;
import java.util.HashMap;
import java.util.Stack;
/**
* Q155
*/
class MinStack {
/**
* initialize your data structure here.
*/
Stack<Integer> stack = new Stack<>();
public MinStack() {
}
public void push(int val) {
if (stack.isEmpty()) {
stack.push(val);
stack.push(val);
} else {
int minVal = stack.peek();
if (val < minVal) {
stack.push(val);// 最小值对应的元素
stack.push(val);// 最小值
} else {
stack.push(val);// 最小值对应的元素
stack.push(minVal);// 最小值
}
}
}
public void pop() {
stack.pop();// 最小值
stack.pop();// 最小值对应的元素
}
public int top() {
int temp1 = stack.pop(); // 最小值
int temp2 = stack.pop(); // 最小值对应的元素
stack.push(temp2);
stack.push(temp1);
return temp2;
}
public int getMin() {
return stack.peek();
}
public static void main(String[] args) {
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
System.out.println(minStack.getMin());
minStack.pop();
System.out.println(minStack.getMin());
}
}