LC.P1670[设计前中后队列]

方法一:两个双端队列

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
class FrontMiddleBackQueue {

Deque<Integer> left;
Deque<Integer> right;

public FrontMiddleBackQueue() {
left = new ArrayDeque<>();
right = new ArrayDeque<>();
}

/**
* 调整长度
* 保证 0 <= right.size() - left.size() <= 1
*/
private void balance() {
if (left.size() > right.size()){
right.offerFirst(left.pollLast());
} else if (right.size() > left.size() + 1) {
left.offerLast(right.pollFirst());
}
}

public void pushFront(int val) {
left.offerFirst(val);
balance();
}

public void pushMiddle(int val) {
if (left.size() < right.size()) left.offerLast(val);
else right.offerFirst(val);
}

public void pushBack(int val) {
right.offerLast(val);
balance();
}

public int popFront() {
// 整个队列为空
if (right.isEmpty()) return -1;
int val = left.isEmpty() ? right.pollFirst() : left.pollFirst();
balance();
return val;
}

public int popMiddle() {
if (right.isEmpty()) return -1;
if (left.size() == right.size()) return left.pollLast();
return right.pollFirst();
}

public int popBack() {
if (right.isEmpty()) return -1;
int val = right.pollLast();
balance();
return val;
}
}

/**
* Your FrontMiddleBackQueue object will be instantiated and called as such:
* FrontMiddleBackQueue obj = new FrontMiddleBackQueue();
* obj.pushFront(val);
* obj.pushMiddle(val);
* obj.pushBack(val);
* int param_4 = obj.popFront();
* int param_5 = obj.popMiddle();
* int param_6 = obj.popBack();
*/
  • 时间复杂度:$O(1)$
  • 空间复杂度:$O(n)$,其中 $n$ 为队列中元素个数