Leetcode 641.設計循環雙端隊列
1 題目描述(Leetcode題目鏈接)
設計實現雙端隊列。
你的實現需要支持以下操作:
- MyCircularDeque(k):構造函數,雙端隊列的大小爲k。
- insertFront():將一個元素添加到雙端隊列頭部。 如果操作成功返回 true。
- insertLast():將一個元素添加到雙端隊列尾部。如果操作成功返回 true。
- deleteFront():從雙端隊列頭部刪除一個元素。 如果操作成功返回 true。
- deleteLast():從雙端隊列尾部刪除一個元素。如果操作成功返回 true。
- getFront():從雙端隊列頭部獲得一個元素。如果雙端隊列爲空,返回 -1。
- getRear():獲得雙端隊列的最後一個元素。 如果雙端隊列爲空,返回 -1。
- isEmpty():檢查雙端隊列是否爲空。
- isFull():檢查雙端隊列是否滿了。
MyCircularDeque circularDeque = new MycircularDeque(3); // 設置容量大小爲3
circularDeque.insertLast(1); // 返回 true
circularDeque.insertLast(2); // 返回 true
circularDeque.insertFront(3); // 返回 true
circularDeque.insertFront(4); // 已經滿了,返回 false
circularDeque.getRear(); // 返回 2
circularDeque.isFull(); // 返回 true
circularDeque.deleteLast(); // 返回 true
circularDeque.insertFront(4); // 返回 true
circularDeque.getFront(); // 返回 4
提示:
- 所有值的範圍爲 [1, 1000]
- 操作次數的範圍爲 [1, 1000]
- 請不要使用內置的雙端隊列庫。
2 題解
本題與第622題的方法完全相同,使用一個固定長度是數組就可以實現。
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self.head = 0
self.tail = 0
self.k = k + 1
self.queue = [-1]*self.k
def insertFront(self, value: int) -> bool:
"""
Adds an item at the front of Deque. Return true if the operation is successful.
"""
if self.isFull():
return False
self.head = (self.head - 1) % self.k
self.queue[self.head] = value
return True
def insertLast(self, value: int) -> bool:
"""
Adds an item at the rear of Deque. Return true if the operation is successful.
"""
if self.isFull():
return False
self.queue[self.tail] = value
self.tail = (self.tail + 1) % self.k
return True
def deleteFront(self) -> bool:
"""
Deletes an item from the front of Deque. Return true if the operation is successful.
"""
if self.isEmpty():
return False
self.queue[self.head] = -1
self.head = (self.head + 1) % self.k
return True
def deleteLast(self) -> bool:
"""
Deletes an item from the rear of Deque. Return true if the operation is successful.
"""
if self.isEmpty():
return False
self.tail = (self.tail - 1) % self.k
self.queue[self.tail] = -1
return True
def getFront(self) -> int:
"""
Get the front item from the deque.
"""
return self.queue[self.head]
def getRear(self) -> int:
"""
Get the last item from the deque.
"""
return self.queue[(self.tail - 1) % self.k]
def isEmpty(self) -> bool:
"""
Checks whether the circular deque is empty or not.
"""
return self.head == self.tail
def isFull(self) -> bool:
"""
Checks whether the circular deque is full or not.
"""
return (self.tail + 1) % self.k == self.head
# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(k)
# param_1 = obj.insertFront(value)
# param_2 = obj.insertLast(value)
# param_3 = obj.deleteFront()
# param_4 = obj.deleteLast()
# param_5 = obj.getFront()
# param_6 = obj.getRear()
# param_7 = obj.isEmpty()
# param_8 = obj.isFull()