上次编辑到这里,代码来自缓存 点击恢复默认模板
class MyCircularQueue {
public:
MyCircularQueue(int k) {
}
bool enQueue(int value) {
}
bool deQueue() {
}
int Front() {
}
int Rear() {
}
bool isEmpty() {
}
bool isFull() {
}
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue* obj = new MyCircularQueue(k);
* bool param_1 = obj->enQueue(value);
* bool param_2 = obj->deQueue();
* int param_3 = obj->Front();
* int param_4 = obj->Rear();
* bool param_5 = obj->isEmpty();
* bool param_6 = obj->isFull();
*/
golang 解法, 执行用时: 12 ms, 内存消耗: 6.7 MB, 提交时间: 2022-08-02 14:16:07
type MyCircularQueue struct {
front, rear int
elements []int
}
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{elements: make([]int, k+1)}
}
func (q *MyCircularQueue) EnQueue(value int) bool {
if q.IsFull() {
return false
}
q.elements[q.rear] = value
q.rear = (q.rear + 1) % len(q.elements)
return true
}
func (q *MyCircularQueue) DeQueue() bool {
if q.IsEmpty() {
return false
}
q.front = (q.front + 1) % len(q.elements)
return true
}
func (q MyCircularQueue) Front() int {
if q.IsEmpty() {
return -1
}
return q.elements[q.front]
}
func (q MyCircularQueue) Rear() int {
if q.IsEmpty() {
return -1
}
return q.elements[(q.rear-1+len(q.elements))%len(q.elements)]
}
func (q MyCircularQueue) IsEmpty() bool {
return q.rear == q.front
}
func (q MyCircularQueue) IsFull() bool {
return (q.rear+1)%len(q.elements) == q.front
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* obj := Constructor(k);
* param_1 := obj.EnQueue(value);
* param_2 := obj.DeQueue();
* param_3 := obj.Front();
* param_4 := obj.Rear();
* param_5 := obj.IsEmpty();
* param_6 := obj.IsFull();
*/
python3 解法, 执行用时: 64 ms, 内存消耗: 15.6 MB, 提交时间: 2022-08-02 14:13:46
class MyCircularQueue:
def __init__(self, k: int):
self.front = self.rear = 0
self.elements = [0] * (k + 1)
def enQueue(self, value: int) -> bool:
if self.isFull():
return False
self.elements[self.rear] = value
self.rear = (self.rear + 1) % len(self.elements)
return True
def deQueue(self) -> bool:
if self.isEmpty():
return False
self.front = (self.front + 1) % len(self.elements)
return True
def Front(self) -> int:
return -1 if self.isEmpty() else self.elements[self.front]
def Rear(self) -> int:
return -1 if self.isEmpty() else self.elements[(self.rear - 1) % len(self.elements)]
def isEmpty(self) -> bool:
return self.rear == self.front
def isFull(self) -> bool:
return (self.rear + 1) % len(self.elements) == self.front