设计循环队列——写起来最清爽的还使用原生的deque 双端队列

622. 设计循环队列

难度中等89收藏分享切换为英文关注反馈

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。

循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。

你的实现应该支持如下操作:

  • MyCircularQueue(k): 构造器,设置队列长度为 k 。
  • Front: 从队首获取元素。如果队列为空,返回 -1 。
  • Rear: 获取队尾元素。如果队列为空,返回 -1 。
  • enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
  • deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
  • isEmpty(): 检查循环队列是否为空。
  • isFull(): 检查循环队列是否已满。

示例:

MyCircularQueue circularQueue = new MycircularQueue(3); // 设置长度为 3

circularQueue.enQueue(1);  // 返回 true

circularQueue.enQueue(2);  // 返回 true

circularQueue.enQueue(3);  // 返回 true

circularQueue.enQueue(4);  // 返回 false,队列已满

circularQueue.Rear();  // 返回 3

circularQueue.isFull();  // 返回 true

circularQueue.deQueue();  // 返回 true

circularQueue.enQueue(4);  // 返回 true

circularQueue.Rear();  // 返回 4
 

提示:

  • 所有的值都在 0 至 1000 的范围内;
  • 操作数将在 1 至 1000 的范围内;
  • 请不要使用内置的队列库。
from collections import deque

class MyCircularQueue:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the queue to be k.
        """
        self.size = k
        self.q = deque(maxlen=k)

    def enQueue(self, value: int) -> bool:
        """
        Insert an element into the circular queue. Return true if the operation is successful.
        """
        if self.isFull():
            return False
        self.q.append(value)
        return True        

    def deQueue(self) -> bool:
        """
        Delete an element from the circular queue. Return true if the operation is successful.
        """
        if self.isEmpty():
            return False
        self.q.popleft()
        return True

    def Front(self) -> int:
        """
        Get the front item from the queue.
        """
        if self.isEmpty():
            return -1
        return self.q[0]

    def Rear(self) -> int:
        """
        Get the last item from the queue.
        """
        if self.isEmpty():
            return -1
        return self.q[-1]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular queue is empty or not.
        """
        return len(self.q) == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular queue is full or not.
        """
        return len(self.q) == self.size

# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()

641. 设计循环双端队列

难度中等26收藏分享切换为英文关注反馈

设计实现双端队列。
你的实现需要支持以下操作:

  • 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]
  • 请不要使用内置的双端队列库。
from collections import deque

class MyCircularDeque:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        """
        self.cap = k
        self.q = deque(maxlen=k)

    def insertFront(self, value: int) -> bool:
        """
        Adds an item at the front of Deque. Return true if the operation is successful.
        """
        if len(self.q) < self.cap:
            self.q.appendleft(value)
            return True
        return False                

    def insertLast(self, value: int) -> bool:
        """
        Adds an item at the rear of Deque. Return true if the operation is successful.
        """
        if len(self.q) < self.cap:
            self.q.append(value)
            return True
        return False 

    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.q.popleft()
        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.q.pop()
        return True

    def getFront(self) -> int:
        """
        Get the front item from the deque.
        """
        if self.isEmpty():
            return -1
        return self.q[0]

    def getRear(self) -> int:
        """
        Get the last item from the deque.
        """
        if self.isEmpty():
            return -1
        return self.q[-1]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular deque is empty or not.
        """
        return len(self.q) == 0        

    def isFull(self) -> bool:
        """
        Checks whether the circular deque is full or not.
        """
        return len(self.q) == self.cap

# 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()

原文地址:https://www.cnblogs.com/bonelee/p/12545559.html

时间: 2024-08-23 19:52:34

设计循环队列——写起来最清爽的还使用原生的deque 双端队列的相关文章

deque双端队列容器

C++中的STL还是比较有用的,尤其是在做科研实现算法的时候,之前也有用过,但是没怎么系统地学过,因此最近找了本书,大致浏览了一下,叶志军的那本<C++ STL开发技术导引>,科普.入门性质的一本书,写得比较浅[呵呵,勿喷].下面的内容大部分是摘自该书. deque双端队列容器(double-ended queue),可以在尾部.头部插入.删除元素,采用分块的线性结构来存储数据,两个迭代器分别指向容器的首尾元素,以deque块为单位进行内存分配,使用二级的Map进行管理. 创建deque对象

std::deque双端队列介绍

在建立vector容器时,一般来说伴随这建立空间->填充数据->重建更大空间->复制原空间数据->删除原空间->添加新数据,如此反复,保证vector始终是一块独立的连续内存空间:在建立deque容器时,一般便随着建立空间->建立数据->建立新空间->填充新数据,如此反复,没有原空间数据的复制和删除过程,是由多个连续的内存空间组成的. C++ STL容器deque和vector很类似,也是采用动态数组来管理元素. 与vector不同的是deque的动态数组首

stl之deque双端队列容器

deque与vector很相似,不仅能够在尾部插入和删除元素,还能够在头部插入和删除. 只是当考虑到容器元素的内存分配策略和操作性能时.deque相对vector较为有优势. 头文件 #include<deque> 创建deque对象 1)deque();//创建一个没有不论什么元素的deque对象. deque<int> d 2)deque(size_typen);//创建一个具有n个元素的deque对象.每一个元素採用它的类型下的默认值. deque<int> d(

Deque 双端队列

Deque允许在队列的头部或尾部进行出队和入队操作 LinkedBlockingDeque是一个线程安全的双端队列实现,可以说他是最为复杂的一种队列,在内部实现维护了前端和后端节点,但是其没有实现读写分离,因此同一时间只能有一个线程对其进行操作.在高并发中性能要远低于其他BlockingQueue.更要低于ConcurrentLinkedQueue,在jdk早期有一个非线程安全的Deque就是ArrayDeque了,java6里添加了LinkedBlockingDeque来弥补多线程场景下线程安

deque双端队列容器(对象创建,数组、迭代器方式访问,元素的赋值、插入、删除等)

deque与vector非常相似,不仅可以在尾部插入和删除元素,还可以在头部插入和删除.不过当考虑到容器元素的内存分配策略和操作性能时,deque相对vector较为有优势. 头文件 #include<deque> 创建deque对象 1)deque();//创建一个没有任何元素的deque对象. deque<int> d 2)deque(size_typen);//创建一个具有n个元素的deque对象,每个元素采用它的类型下的默认值. deque<int> d(10)

STL容器:deque双端队列学习

所谓deque,是"double-ended queue"的缩写; 它是一种动态数组形式,可以向两端发展,在尾部和头部插入元素非常迅速; 在中间插入元素比较费时,因为需要移动其它元素;(No) 双端队列容器,在序列的两端放置和删除元素是高效的; 而vector只是在序列末尾插入才是高效的. C++ Code 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495

c++ deque 双端队列

双端队列: 函数 描述 c.assign(beg,end)c.assign(n,elem)  将[beg; end)区间中的数据赋值给c.将n个elem的拷贝赋值给c. c.at(idx)  传回索引idx所指的数据,如果idx越界,抛出out_of_range. c.back()  传回最后一个数据,不检查这个数据是否存在. c.begin()  传回迭代器重的可一个数据. c.clear()  移除容器中所有数据. deque<Elem> cdeque<Elem> c1(c2)

[程序员代码面试指南]栈和队列-最大值减去最小值 小于或等于num 的子数组的数量(双端队列)

题目 给定数组arr和整数num,求数组的子数组中有多少个的满足"最大值减去最小值<=num". 解题思路 分析题目,有结论: 如果数组arr[i...j]满足条件,则它的每一个子数组都满足条件. 如果数组arr[i...j]不满足条件,则包含它的每一个数组都不满足条件. 数据结构:用i.j表示当前窗口,分别使用两个双端队列维护窗口的最大值和最小值. 具体地,每次更新两个双端队列,检查当前的窗口是否满足条件,满足则j++,不满足则cnt+=j-i,更新双端队列,i++,j不变.若

deque双端队列用法

#include <iostream> #include <cstdio> #include <deque> #include <algorithm> using namespace std; deque<int> dq; int main() { dq.push_front(102);///插入头部 dq.push_back(101);///插入尾部 sort(dq.begin(),dq.end()); deque<int>::it