forked from super30admin/Design-1
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
Latest commit
37 lines (31 loc) · 725 Bytes
/
Copy pathMinStack.java
File metadata and controls
37 lines (31 loc) · 725 Bytes
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
//Design a min stack
//Time Complexity : O(1)
//Space Complexity : O(n)
importjava.util.Stack;
classMinStack {
Stack<Integer> minStack;
intmin;
publicMinStack() {
this.minStack = newStack<>();
this.min = Integer.MAX_VALUE;
}
publicvoidpush(intval) {
//Push previous minimum & new minimum to stack when minimum changes
if(min >= val) {
minStack.push(min);
min = val;
}
minStack.push(val);
}
publicvoidpop() {
if(min == minStack.pop()) {
min = minStack.pop();
}
}
publicinttop() {
returnminStack.peek();
}
publicintgetMin() {
returnmin;
}
}