leetcdoe 1670.设计前中后队列
1.题目要求:
2.题目实列:
输入:
["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
[[], [1], [2], [3], [4], [], [], [], [], []]
输出:
[null, null, null, null, null, 1, 3, 4, 2, -1]
解释:
FrontMiddleBackQueue q = new FrontMiddleBackQueue();
q.pushFront(1); // [1]
q.pushBack(2); // [1, 2]
q.pushMiddle(3); // [1, 3, 2]
q.pushMiddle(4); // [1, 4, 3, 2]
q.popFront(); // 返回 1 -> [4, 3, 2]
q.popMiddle(); // 返回 3 -> [4, 2]
q.popMiddle(); // 返回 4 -> [2]
q.popBack(); // 返回 2 -> []
q.popFront(); // 返回 -1 -> [] (队列为空)
提示:
1 <= val <= 109
最多调用 1000 次 pushFront, pushMiddle, pushBack, popFront, popMiddle 和 popBack 。
3.做题思想:
c++采用deque容器作为基础更容易, 根据题目要求要理解中间的下标的位置
4.题目代码:
class FrontMiddleBackQueue {
public:
deque<int> array;
FrontMiddleBackQueue() {
array.clear();
}
//前方插入值
void pushFront(int val) {
array.push_front(val);
}
//中间插入值
void pushMiddle(int val) {
if(array.size() == 0){
array.push_back(val);
}else{
int index = (0 + (array.size() - 1)) / 2;
if(array.size() % 2 == 0){
array.insert(array.begin() + index + 1,val);
}else{
array.insert(array.begin() + index,val);
}
}
}
//后方插入值
void pushBack(int val) {
array.push_back(val);
}
//前出
int popFront() {
if(array.size() != 0){
int front_element = array.front();
array.pop_front();
return front_element;
}else{
return -1;
}
}
//中间出值
int popMiddle(){
if(array.size() != 0){
int index = (0 + array.size() - 1) / 2;
int mid_element = array[index];
array.erase(array.begin() + index);
return mid_element;
}else{
return -1;
}
}
//后方出值
int popBack() {
if(array.size() != 0){
int back_element = array.back();
array.pop_back();
return back_element;
}else{
return -1;
}
}
};
/**
* 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();
*/