forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
46 lines (42 loc) · 1.12 KB
/
MinStack.java
File metadata and controls
46 lines (42 loc) · 1.12 KB
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
import java.util.*;
class MinStack {
Stack<Integer> data = new Stack<Integer>();
Stack<Integer> minData = new Stack<Integer>();
public MinStack() {}
public void push(int x) {
data.push(x);
if (minData.isEmpty() || x <= getMin()) {
minData.push(x);
}
}
public int pop() {
if (!data.isEmpty()) {
int v = data.pop();
if (v == getMin()) {
minData.pop();
}
return v;
} else {
throw new RuntimeException();
}
}
public int top() {
if (data.isEmpty()) throw new RuntimeException();
return data.peek();
}
public int getMin() {
if (minData.isEmpty()) throw new RuntimeException();
return minData.peek();
}
public static void main(String[] args) {
MinStack ms = new MinStack();
ms.push(-1);
ms.push(-2);
ms.push(0);
System.out.format("%d\n", ms.getMin());
ms.pop();
System.out.format("%d\n", ms.getMin());
ms.pop();
System.out.format("%d\n", ms.getMin());
}
}