设计实现双端循环队列
641. Design Circular Deque
Design your implementation of the circular double-ended queue (deque).
Your implementation should support following operations:
MyCircularDeque(k): Constructor, set the size of the deque to be k. insertFront(): Adds an item at the front of Deque. Return true if the operation is successful. insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful. deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful. deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful. getFront(): Gets the front item from the Deque. If the deque is empty, return -1. getRear(): Gets the last item from Deque. If the deque is empty, return -1. isEmpty(): Checks whether Deque is empty or not. isFull(): Checks whether Deque is full or not.
Example:
MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3 circularDeque.insertLast(1); // return true circularDeque.insertLast(2); // return true circularDeque.insertFront(3); // return true circularDeque.insertFront(4); // return false, the queue is full circularDeque.getRear(); // return 2 circularDeque.isFull(); // return true circularDeque.deleteLast(); // return true circularDeque.insertFront(4); // return true circularDeque.getFront(); // return 4
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.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/design-circular-deque |
使用链表来实现双端队列
使用链表实现起来较为容易,记录下队头与队尾的指针,对其节点进行添加与删除,就可以很容易的实现双端队列
还是看代码吧
/** |
使用数组来实现双端队列
此使用循环队列来实现,在实现上比链式队列,会复杂很多,队尾的处理与单循环队列无异,但还需要处理队头的指针位置时,在队头插入与删除操作,我画了个图,比较直观点
代码实现
|
求滑动窗口的最大值
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3 Output: [3,3,5,5,6,7] Explanation:
Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Note: You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up: Could you solve it in linear time?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sliding-window-maximum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 |
使用双端队实现
此实现就是在窗口中求最大值。可用使用一个双端队列实现,双端队列的大小为窗口的大小,每放入一个元素,从队头移除一个元素,又向队尾追加一个元素。在队列中求中最大值。还是来画个图,更为直观点吧!
使用java原生的LinkedList实现
|
使用循环双端队实现
使用循环队列来替代linkedList,解题思路与前面队列一致
|
设计实现一个循环双端队列
Design your implementation of the circular queue. |
我的实现
特别需要注意判断空
|