-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution59-2.java
More file actions
36 lines (29 loc) · 1.24 KB
/
Solution59-2.java
File metadata and controls
36 lines (29 loc) · 1.24 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
public class MaxQueue {
Queue<Integer> queue;
LinkedList<Integer> max;
public MaxQueue() {
queue = new LinkedList<>();
max = new LinkedList<>();// LinkedList是双端链表
}
public int max_value() {
return max.size() == 0 ? -1 : max.getFirst();
}
public void push_back(int value) {
queue.add(value);
while (max.size() != 0 && max.getLast() < value) {// 注意:这里第二个判断条件不能带等号,即max中对于当前queue中的具有相同值的元素会全部存储,而不是存储最近的那个。
max.removeLast();
}
max.add(value);
}
public int pop_front() {
if (max.size() != 0 && queue.peek().equals(max.getFirst()))// Integer类型的值的比较不能直接使用==
max.removeFirst();
return queue.size() == 0 ? -1 : queue.poll();
}
/**
* Your MaxQueue object will be instantiated and called as such: MaxQueue obj =
* new MaxQueue(); int param_1 = obj.max_value(); obj.push_back(value); int
* param_3 = obj.pop_front();
*/
}
// 作者:mo-fei-25 链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/solution/mian-shi-ti-59-ii-javashi-xian-yuan-li-he-mian-shi/