力扣1670.设计前中后队列
-
两个双端队列
-
- 始终保证right.size() >= left.size()
- 向中间插入时如果一样长 就插入right
- 如果right长就插入left
cpp
class FrontMiddleBackQueue {
private:
deque<int> left;
deque<int> right;
//保证left.size() + 1 >= right.size() >= left.size()
void banlance()
{
if(left.size() > right.size())
{
right.push_front(left.back());
left.pop_back();
}
else if(right.size() > left.size() + 1)
{
left.push_back(right.front());
right.pop_front();
}
}
public:
FrontMiddleBackQueue() {
}
void pushFront(int val) {
left.push_front(val);
banlance();
}
void pushMiddle(int val) {
if(left.size() < right.size())
left.push_back(val);
else
right.push_front(val);
}
void pushBack(int val) {
right.push_back(val);
banlance();
}
int popFront() {
if(right.empty())
return -1;
int val;
if(left.empty())
{
val = right.front();
right.pop_front();
}
else
{
val = left.front();
left.pop_front();
}
banlance();
return val;
}
int popMiddle() {
if(right.empty())
return -1;
int val;
if(left.size() == right.size())
{
val = left.back();
left.pop_back();
}
else
{
val = right.front();
right.pop_front();
}
return val;
}
int popBack() {
if(right.empty())
return -1;
int val = right.back();
right.pop_back();
banlance();
return val;
}
};