-
Notifications
You must be signed in to change notification settings - Fork 13
/
MaxQueue.java
47 lines (34 loc) · 849 Bytes
/
MaxQueue.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
37
38
39
40
41
42
43
44
45
46
47
package leetcode.queue.monotonic;
import java.util.ArrayDeque;
import java.util.Deque;
public class MaxQueue {
Deque<Integer> max;
Deque<Integer> queue;
public MaxQueue() {
max = new ArrayDeque<>();
queue = new ArrayDeque<>();
}
public int max_value() {
if (queue.isEmpty()) {
return -1;
}
return max.peekFirst();
}
public void push_back(int value) {
queue.addLast(value);
while (!max.isEmpty() && value > max.peekLast()) {
max.pollLast();
}
max.addLast(value);
}
public int pop_front() {
if (queue.isEmpty()) {
return -1;
}
Integer res = queue.pollFirst();
if (res.equals(max.peekFirst())) {
max.pollFirst();
}
return res;
}
}