当前位置:网站首页>LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
2022-08-02 19:37:00 【HERODING23】

解题思路
解决本题的关键在于定义好数据结构类型,首先定义一个长度为k的数组,再定义几个变量,当前要插入节点的下标index,当前队列长度len,以及最大队列容量n,入队列首先判断是否满,不满就往index位置插入即可,出队列直接len–,不需要对删除的数进行操作,获取队首元素就需要从index位置往前数len的长度,注意是循环数组,所以有取余操作,队尾就是index的前一个位置的数,也需要注意取余操作,最后就是判断空和满的函数,直接根据len是否为0或者n进行返回,代码如下:
代码
class MyCircularQueue {
private:
vector<int> q;
int len;
int n;
int index;
public:
MyCircularQueue(int k) {
q = vector<int>(k, 0);
len = 0;
index = 0;
n = k;
}
bool enQueue(int value) {
if(len < n) {
q[index] = value;
index ++;
index %= n;
len ++;
return true;
}
return false;
}
bool deQueue() {
if(len == 0) {
return false;
}
len --;
return true;
}
int Front() {
if(len == 0) {
return -1;
}
return q[(index + n - len) % n];
}
int Rear() {
if(len == 0) {
return -1;
}
return q[(index + n - 1) % n];
}
bool isEmpty() {
return len == 0;
}
bool isFull() {
return len == n;
}
};
/** * Your MyCircularQueue object will be instantiated and called as such: * MyCircularQueue* obj = new MyCircularQueue(k); * bool param_1 = obj->enQueue(value); * bool param_2 = obj->deQueue(); * int param_3 = obj->Front(); * int param_4 = obj->Rear(); * bool param_5 = obj->isEmpty(); * bool param_6 = obj->isFull(); */
边栏推荐
- es 官方诊断工具
- Geoserver+mysql+openlayers2
- Office2021 安装MathType
- 【LeetCode】1161. 最大层内元素和
- openlayers版本更新差别
- spack install reports an error /tmp/ccBDQNaB.s: Assembler message:
- SQL Server数据类型转换函数cast()和convert()详解
- 什么是现场服务管理系统(FSM)?有什么好处?
- JWT学习
- 4 kmiles join YiSheng group, with more strong ability of digital business, accelerate China's cross-border electricity full domain full growth
猜你喜欢

Office2021 安装MathType

什么是现场服务管理系统(FSM)?有什么好处?

当TIME_WAIT状态的TCP正常挥手,收到SYN后…

SCANIA SCANIA OTL tag is introduced

idea 配置resin

7月29-31 | APACHECON ASIA 2022

Parse common methods in the Collection interface that are overridden by subclasses

Caldera(一)配置完成的虚拟机镜像及admin身份简单使用

你想要的宏基因组-微生物组知识全在这(2022.8)

元宇宙001 | 情绪无法自控?元宇宙助你一臂之力
随机推荐
让你的应用完美适配平板
Introduction of uncommon interfaces of openlayers
es 读流程源码解析
Redis cluster configuration
【软件工程导论】软件工程导论笔记
光源控制器接口定义说明
Parse the commonly used methods in the List interface that are overridden by subclasses
MySQL安装配置教程(超级详细)
实现客户服务自助,打造产品知识库
Electron User Guide Beginning Experience
软考 ----- UML设计与分析(下)
[安洵杯 2019]easy_web
TPAMI2022 | TransCL:基于Transformer的压缩学习,更灵活更强大
2022-07-26
Shell: conditional statements
治疗 | 如何识别和处理消极想法
The so-called fighting skill again gao also afraid of the chopper - partition, depots, table, and the merits of the distributed
你想要的宏基因组-微生物组知识全在这(2022.8)
程序员也许都缺一个“二舅”精神
Lvm逻辑卷