-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathMaxQueue.java
46 lines (40 loc) · 975 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
package LeetCode.CodingInterviews.Java;
import java.util.*;
class MaxQueue {
List<Integer> queue;
int i, cur, max;
public MaxQueue() {
i = 0;
cur = -1;
queue = new ArrayList<>();
max = -1;
}
public int max_value() {
if (max == -1 || max >= queue.size())
return -1;
return queue.get(max);
}
public void push_back(int value) {
++cur;
queue.add(value);
if (max == -1)
max = cur;
if (queue.get(max) <= value)
max = cur;
}
public int pop_front() {
if (queue.isEmpty() || i >= queue.size())
return -1;
int first = queue.get(i);
if (i == max) {
int j = ++i;
++max;
while (j < queue.size()) {
max = queue.get(max) <= queue.get(j) ? j : max;
++j;
}
} else
++i;
return first;
}
}