forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-front-middle-back-queue.cpp
75 lines (65 loc) · 1.58 KB
/
design-front-middle-back-queue.cpp
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
// Time: O(1)
// Space: O(n)
class FrontMiddleBackQueue {
public:
FrontMiddleBackQueue() {
}
void pushFront(int val) {
left_.emplace_front(val);
balance();
}
void pushMiddle(int val) {
if (size(left_) > size(right_)) {
right_.emplace_front(left_.back());
left_.pop_back();
}
left_.emplace_back(val);
}
void pushBack(int val) {
right_.emplace_back(val);
balance();
}
int popFront() {
int result = -1;
if (!empty(left_)) {
result = left_.front();
left_.pop_front();
}
balance();
return result;
}
int popMiddle() {
int result = -1;
if (!empty(left_)) {
result = left_.back();
left_.pop_back();
}
balance();
return result;
}
int popBack() {
int result = -1;
if (!empty(right_)) {
result = right_.back();
right_.pop_back();
} else if (!empty(left_)) {
result = left_.back();
left_.pop_back();
}
balance();
return result;
}
private:
void balance() {
if (size(left_) > size(right_) + 1) {
right_.emplace_front(left_.back());
left_.pop_back();
} else if (size(left_) < size(right_) ) {
left_.emplace_back(right_.front());
right_.pop_front();
}
}
// using list<int> is also fine but slower
deque<int> left_;
deque<int> right_;
};