原题链接在这里:https://leetcode.com/problems/design-circular-deque/
题目:
Design your implementation of the circular double-ended queue (deque).
Your implementation should support following operations:
<code>MyCircularDeque(k)</code>: Constructor, set the size of the deque to be k.
<code>insertFront()</code>: Adds an item at the front of Deque. Return true if the operation is successful.
<code>insertLast()</code>: Adds an item at the rear of Deque. Return true if the operation is successful.
<code>deleteFront()</code>: Deletes an item from the front of Deque. Return true if the operation is successful.
<code>deleteLast()</code>: Deletes an item from the rear of Deque. Return true if the operation is successful.
<code>getFront()</code>: Gets the front item from the Deque. If the deque is empty, return -1.
<code>getRear()</code>: Gets the last item from Deque. If the deque is empty, return -1.
<code>isEmpty()</code>: Checks whether Deque is empty or not.
<code>isFull()</code>: Checks whether Deque is full or not.
Example:
Note:
All values will be in the range of [0, 1000].
The number of operations will be in the range of [1, 1000].
Please do not use the built-in Deque library.
题解:
Use an array to maintain values.
start index pointing to queue head, initialized as -1.
end index pointing to queue tail, initialized as -1.
When insertFront, if start == -1, assign start as 0, else start = (start - 1 + k) % k. Assign new value to arr[start]. If end is -1, need to update end = start. This only happens at the beginning.
When insertLast, end = (end + 1) % k. Assign new value to arr[end]. If start is -1, need to update start = end. This only happends at the begining.
deleteFront, move start + 1.
deleteLast, move end - 1.
Time Complexity: MyCircularDeque, O(1). insertFront, O(1). insertLast, O(1). deleteFront, O(1). deleteLast, O(1). getFront, O(1). getRear, O(1). isEmpty, O(1). isEmpty, O(1).
Space: O(k).
AC Java:
类似Design Circular Queue.