题目链接:https://leetcode.cn/problems/design-circular-deque/description/
队列经典题目,考察各种空满条件。很多细节需要注意:
- vector 设置大小使用 resize
- front 和 back 指针不是对称的,front 指向队首元素的前一格,back 指向队尾元素,这非常重要,因为这样才能保证
front == back
时为空 - 下面的解法没有使用额外一个空间,从而导致
front == back
时可能是空,也可能是满,所以使用了两个标志位 isfull 和 isempty,略显麻烦。官方解答中使用了 k+1 个空间,满的条件是(front+1)%size == back
,其中size == k+1
。 - -1%12=-11,注意 % 求余时,结果的正负取决于 % 左边操作数的正负,因此
back = back == 0 ? size -1 : back - 1
或者back = (back - 1 + size) % size
class MyCircularDeque {
public:
vector<int> array;
int front;
int back;
int size;
bool isfull;
bool isempty;
MyCircularDeque(int k) {
array.resize(k);
size = k;
isfull = false;
isempty = true;
front = 0;
back = 0;
}
bool insertFront(int value) {
if (isFull()) {
return false;
}
array[front] = value;
front = (front + 1) % size;
if (front == back) {
isfull = true;
}
isempty = false;
return true;
}
bool insertLast(int value) {
if (isFull()) {
return false;
}
back = back == 0 ? size - 1 : back - 1;
array[back] = value;
if (front == back) {
isfull = true;
}
isempty = false;
return true;
}
bool deleteFront() {
if (isEmpty()) {
return false;
}
front = front == 0 ? size - 1 : front - 1;
if (front == back) {
isempty = true;
}
isfull = false;
return true;
}
bool deleteLast() {
if (isEmpty()) {
return false;
}
back = (back + 1) % size;
if (front == back) {
isempty = true;
}
isfull = false;
return true;
}
int getFront() {
if (isEmpty()) {
return -1;
}
return array[front == 0 ? size -1 : front-1];
}
int getRear() {
if (isEmpty()) {
return -1;
}
return array[back];
}
bool isEmpty() {
return isempty;
}
bool isFull() {
return isfull;
}
};