-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathMinQueue.java
More file actions
39 lines (31 loc) · 828 Bytes
/
Copy pathMinQueue.java
File metadata and controls
39 lines (31 loc) · 828 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
38
39
// Time Complexity : O(1) for push, O(1) for min and O(1) for top
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this :No
class MinStack {
int min;
Stack<Integer> stack;
Stack<Integer> minStack;
public MinStack() {
this.min = Integer.MAX_VALUE;
stack = new Stack<>();
minStack = new Stack<>();
minStack.push(min);
}
public void push(int val) {
stack.push(val);
min = Math.min(min,val);
minStack.push(min);
}
public void pop() {
stack.pop();
minStack.pop();
min = minStack.peek();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}