-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinQueueTemplate.java
More file actions
102 lines (80 loc) · 1.79 KB
/
Copy pathMinQueueTemplate.java
File metadata and controls
102 lines (80 loc) · 1.79 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.util.Stack;
/*
In this class, Queue is implemented with 2 stacks, and you can get minimum value of queue in O(1) time.
*/
public class MinQueueTemplate {
private static class Pair{
int val;
int min;
public Pair(int x, int y){
val=x;
min=y;
}
}
private static class MinQueue{
Stack<Pair> stackFirst;
Stack<Pair> stackSecond;
public MinQueue(){
stackFirst = new Stack<Pair>();
stackSecond = new Stack<Pair>();
}
public void add(int x){
if (stackFirst.isEmpty()){
stackFirst.push(new Pair(x,x));
}
else{
Pair top=stackFirst.peek();
int min=Math.min(top.min, x);
stackFirst.push(new Pair(x,min));
}
}
public int remove(){
if(!stackSecond.isEmpty()){
Pair pop=stackSecond.pop();
return pop.val;
}
else{
if(stackFirst.isEmpty()){
return -1;
}
while(!stackFirst.isEmpty()){
Pair f=stackFirst.pop();
int min=f.val;
if(!stackSecond.isEmpty()){
Pair top=stackSecond.peek();
min=Math.min(top.min, min);
}
stackSecond.push(new Pair(f.val,min));
}
Pair pop=stackSecond.pop();
return pop.val;
}
}
public int getMin(){
int min=Integer.MAX_VALUE;
if(!stackSecond.isEmpty()){
Pair top=stackSecond.peek();
min=Math.min(min, top.min);
}
if(!stackFirst.isEmpty()){
Pair top=stackFirst.peek();
min=Math.min(min, top.min);
}
return min;
}
}
public static void main(String[] args) {
MinQueue minq = new MinQueue();
minq.add(0);
System.out.println("min="+minq.getMin());
minq.add(5);
System.out.println("min="+minq.getMin());
minq.add(3);
System.out.println("min="+minq.getMin());
minq.remove();
minq.remove();
minq.remove();
minq.add(6);
System.out.println("min="+minq.getMin());
}
}