做这道题踩了几个坑。
首先是要注意好逻辑结构,什么时候是空的,什么时候是非空的,什么时候enqueue和dequeue时要移动指针,什么时候不需要。
其次是注意类内变量是要在__init__内定义,而不是在__init__外定义在__init__内初始化。
最后是题目虽然说操作数在1-1000中间,但测试样例中有输入为0的情况,因此空位不能设置为0,最好设置为-1,这样front()和rear()定义不需要判断queue是否空,直接取值即可。
代码为:
class MyCircularQueue(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the queue to be k.
:type k: int
"""
self.queue = []
for _ in range(k):
self.queue.append(-1)
self.front = 0
self.rear = 0
return
def enQueue(self, value):
"""
Insert an element into the circular queue. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull