-
Notifications
You must be signed in to change notification settings - Fork 57
/
Solution.java
36 lines (31 loc) · 875 Bytes
/
Solution.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
/**
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
*
* push(x) -- Push element x onto stack.
* pop() -- Removes the element on top of the stack.
* top() -- Get the top element.
* getMin() -- Retrieve the minimum element in the stack.
*/
class MinStack {
private Stack<Integer> st = new Stack<Integer>();
private Stack<Integer> minSt = new Stack<Integer>();
public void push(int x) {
st.push(x);
if (minSt.isEmpty()) {
minSt.push(x);
} else {
int val = minSt.peek().intValue();
minSt.push(val < x ? val : x);
}
}
public void pop() {
minSt.pop();
st.pop();
}
public int top() {
return st.peek().intValue();
}
public int getMin() {
return minSt.peek().intValue();
}
}