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
44 lines (37 loc) · 900 Bytes
/
Copy pathMinStack.java
File metadata and controls
44 lines (37 loc) · 900 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
40
41
42
43
44
// Time Complexity : O(1)
// Space Complexity : O(N)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
import java.util.* ;
class MinStack {
Stack<Integer> myStk;
Stack<Integer> minStk;
public MinStack() {
myStk = new Stack<>();
minStk = new Stack<>();
}
public void push(int val) {
if(minStk.isEmpty() || minStk.peek() >= val) {
minStk.push(val);
}
myStk.push(val);
}
public void pop() {
int topElement = myStk.pop();
if(minStk.peek() == topElement) {
minStk.pop();
}
}
public int top() {
if (!myStk.isEmpty()) {
return myStk.peek();
}
return -1;
}
public int getMin() {
if (!minStk.isEmpty()) {
return minStk.peek();
}
return -1;
}
}