LeetCode 622. 【Java】622. Design Circular Queue
原题链接
中等
作者:
tt2767
,
2020-03-14 16:39:11
,
所有人可见
,
阅读 752
/**
1. 设计思路:
1.1 两个指针, head 为当前队列头, tail为当前队列尾的下一个位置
1.2 每次取+1模
2. testcase:
容量: 0, 1, 2, 3
3. 这个写法为什么 size = k + 1, 极限当k = 1 时, 此时head == tail == 0,
这时对应的意义为, head 为队列头, tail为队列尾部下一个位置, 即左闭右开, 然而( tail + 1 ) % size 仍然为1 ,无法判断, 所以空出一位
也就是说 tail 应该一直指向 "空"位置, 所以 要多开一个空间
4. 如果要空间恰好为k, 可以使用统计队列元素的方法, 此时 tail = (head + count - 1) % size;
*/
class MyCircularQueue {
/** Initialize your data structure here. Set the size of the queue to be k. */
int head, tail, size;
int[] data;
public MyCircularQueue(int k) {
this.size = k;
this.head = 0;
this.tail = 0;
this.data = new int[k];
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if (isFull()) return false;
tail = isEmpty() ? tail: (tail + 1) % size;
data[tail] = value;
count++;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if (isEmpty()) return false;
count --;
head = (head + 1) % size;
return true;
}
/** Get the front item from the queue. */
public int Front() {
return isEmpty() ? -1 : data[head];
}
/** Get the last item from the queue. */
public int Rear() {
return isEmpty() ? -1 : data[tail];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return count == 0;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return count == size;
}
}
class MyCircularQueue {
/** Initialize your data structure here. Set the size of the queue to be k. */
int head, size, count;
int[] data;
public MyCircularQueue(int k) {
this.size = k;
this.head = 0;
this.count = 0;
this.data = new int[k];
}
private int getTailIndex(){
return (head + count - 1) % size;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if (isFull()) return false;
count++;
data[getTailIndex()] = value;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if (isEmpty()) return false;
count --;
head = (head + 1) % size;
return true;
}
/** Get the front item from the queue. */
public int Front() {
return isEmpty() ? -1 : data[head];
}
/** Get the last item from the queue. */
public int Rear() {
return isEmpty() ? -1 : data[getTailIndex()];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return count == 0;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return count == size;
}
}