forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinStack.java
47 lines (37 loc) · 1.11 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
// Time Complexity : O(1) for all operations
// Space Complexity : O(N) for the extra stack
// Did this code successfully run on Leetcode : Yes
// Approach - Use two Stacks (st and minStack).
//Push - If the element being pushed is smaller than the current minimum push it to minstack.
//Pop - If the element being popped is current minimum. Pop from minstack as well.
//getMin - The element on top of the minstack is the current minimum.
import java.util.Stack;
class MinStack {
Stack<Integer> st;
Stack<Integer> minStack;
public MinStack() {
this.st = new Stack<>();
this.minStack = new Stack<>();
}
public void push(int val) {
st.push(val);
if (minStack.isEmpty() || val <= minStack.peek()) {
minStack.push(val);
}
}
public void pop() {
if (st.isEmpty()) {
return;
}
int poppedVal = st.pop();
if (poppedVal == minStack.peek()) {
minStack.pop();
}
}
public int top() {
return st.peek();
}
public int getMin() {
return minStack.peek();
}
}