-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinstack.java
More file actions
41 lines (36 loc) · 1.06 KB
/
Minstack.java
File metadata and controls
41 lines (36 loc) · 1.06 KB
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> stack;
public MinStack() {
//initialize stack
stack = new Stack<>();
}
public void push(int val) {
//push the value to the list
stack.push(val);
}
public void pop() {
//remove the last element and return it
int value = stack.pop();
}
public int top() {
//return the last element
int value = stack.peek();
return value;
}
public int getMin() {
//copy the stack and sort in reverse order the copied stack inorder not to change the original stack
Stack<Integer> stackcopy = (Stack)stack.clone();
Collections.sort(stackcopy, Collections.reverseOrder());
//return the first element(already reverse sorted, minimum is the last element)
int min = stackcopy.peek();
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/