-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path02MinStack.java
More file actions
30 lines (24 loc) · 807 Bytes
/
02MinStack.java
File metadata and controls
30 lines (24 loc) · 807 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
// Time complexity: O(1) for all operations
// Space complexity: O(n) for the stack
class MinStack {
// Use a pair to store the value and the minimum value at that point
Stack<Pair<Integer, Integer>> stack = new Stack<>();
public void push(int val) {
int min = val;
if (!stack.isEmpty()) {
// Get minimum between the current value and the minimum value of the previous element
min = Math.min(val, stack.peek().getValue());
}
// Push the value and the minimum value to the stack
stack.push(new Pair<>(val, min));
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek().getKey();
}
public int getMin() {
return stack.peek().getValue();
}
}