-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
41 lines (24 loc) · 716 Bytes
/
MinStack.java
File metadata and controls
41 lines (24 loc) · 716 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
class MinStack {
Stack<Integer> elements = new Stack<>();
Stack<Integer> mins = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
elements.push(x);
if(mins.empty() || x <= getMin()) {
mins.push(x);
}
}
public void pop() {
if (elements.empty()) return;
int elem = elements.pop();
if (elem == getMin()) mins.pop();
}
public int top() {
return elements.peek();
}
public int getMin() {
return mins.peek();
}
}