-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathP8.java
More file actions
56 lines (48 loc) · 1.2 KB
/
P8.java
File metadata and controls
56 lines (48 loc) · 1.2 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package stack_and_queue;
import java.util.*;
// Problem Title => Design a stack that supports getMin() in O(1) time and O(1) extra space
class MinimumStack {
Stack<Node> s;
static class Node{
int val;
int min;
public Node(int val,int min){
this.val = val;
this.min = min;
}
}
/** initialize your data structure here. */
public MinimumStack() {
this.s= new Stack<>();
}
public void push(int x) {
if(s.isEmpty())
this.s.push(new Node(x, x));
else{
int min=Math.min(this.s.peek().min,x);
this.s.push(new Node(x, min));
}
}
public int pop() {
return this.s.pop().val;
}
public int top() {
return this.s.peek().val;
}
public int getMin() {
return this.s.peek().min;
}
}
public class P8 {
public static void main (String[] args) {
MinimumStack s = new MinimumStack();
s.push(-1);
s.push(10);
s.push(-4);
s.push(0);
System.out.println(s.getMin());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.getMin());
}
}