题目地址:
https://leetcode.com/problems/design-circular-deque/
设计循环双端队列。初始化时会给定一个capacity,不需要扩容。当添加元素的时候,如果队列满,则返回false,否则添加并返回true;当查看元素时,如果队列空则返回 − 1 -1 −1,否则返回查看所得值;当删除元素时,如果队列空则返回false,否则删除并返回true。
用一个数组表示队列,并用两个指针分别指向队列头和队列尾,再用一个变量记录队列里元素个数。每当添加的时候都需要注意判断当前队列里元素个数是否是 0 0 0,是否是 1 1 1,这两者处理起来不太一样。代码如下:
public class MyCircularDeque {
private int[] deque;
private int front, rear, size, k;
/** Initialize your data structure here. Set the size of the deque to be k. */
public MyCircularDeque(int k) {
deque = new int[k];
this.k = k;
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
public boolean insertFront(int value) {
if (size == k) {
return false;
}
// 如果队列本身为空,此时队头指针等于队尾指针,直接赋值;否则将队头向前移动一步再赋值
if (size == 0) {
deque[front] = value;
} else {
front = (front - 1 + k) % k;
deque[front] = value;
}
size++;
return true;
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
public boolean insertLast(int value) {
if (size == k) {
return false;
}
if (size == 0) {
deque[rear] = value;
} else {
rear = (rear + 1) % k;
deque[rear] = value;
}
size++;
return true;
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
public boolean deleteFront() {
// 如果队列里只有一个元素,那么删除操作的时候队头队尾都不需要移动,只需记录一下size变为0即可
if (size == 0) {
return false;
} else if (size == 1) {
size--;
return true;
}
front = (front + 1) % k;
size--;
return true;
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
public boolean deleteLast() {
if (size == 0) {
return false;
} else if (size == 1) {
size--;
return true;
}
rear = (rear - 1 + k) % k;
size--;
return true;
}
/** Get the front item from the deque. */
public int getFront() {
return isEmpty() ? -1 : deque[front];
}
/** Get the last item from the deque. */
public int getRear() {
return isEmpty() ? -1 : deque[rear];
}
/** Checks whether the circular deque is empty or not. */
public boolean isEmpty() {
return size == 0;
}
/** Checks whether the circular deque is full or not. */
public boolean isFull() {
return size == k;
}
}
除初始化外,所有操作时空复杂度 O ( 1 ) O(1) O(1),初始化时间 O ( 1 ) O(1) O(1),空间 O ( k ) O(k) O(k)。