我的解答20190412
class MyCircularDeque(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the deque to be k.
:type k: int
"""
self.queue = []
self.len = k
def insertFront(self, value):
"""
Adds an item at the front of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull():
return False
else:
self.queue.insert(0,value)
return True
def insertLast(self, value):
"""
Adds an item at the rear of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull():
return False
else:
self.queue.append(value)
return True
def deleteFront(self):
"""
Deletes an item from the front of Deque. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty():
return False
else:
self.queue.pop(0)
return True
def deleteLast(self):
"""
Deletes an item from the rear of Deque. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty():
return False
else:
self.queue.pop()
return True
def getFront(self):
"""
Get the front item from the deque.
:rtype: int
"""
if self.isEmpty():
return -1
else:
return self.queue[0]
def getRear(self):
"""
Get the last item from the deque.
:rtype: int
"""
if self.isEmpty():
return -1
else:
return self.queue[-1]
def isEmpty(self):
"""
Checks whether the circular deque is empty or not.
:rtype: bool
"""
if len(self.queue)==0:
return True
def isFull(self):
"""
Checks whether the circular deque is full or not.
:rtype: bool
"""
if len(self.queue) == self.len:
return True
反思1:
import collections
self.data = collections.deque()
#速度更快,在队列两端插入或删除元素时间复杂度都是 O(1)
#区别于列表,在列表的开头插入或删除元素的时间复杂度为 O(N) 。
链接:《python cookbook》1.3 保留最后 N 个元素
反思2:
if len(self.queue) == self.len:
return True
#直接替换成
return len(self.queue) == self.len