当前位置:网站首页>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(); */
边栏推荐
猜你喜欢

openlayers不常用接口介绍

LeetCode - 105. 从前序与中序遍历序列构造二叉树;023.合并K个升序链表

ShapeableImageView 的使用,告别shape、三方库

Mysql安装流程 【压缩版】

ShardingSphere-proxy +PostgreSQL实现读写分离(静态策略)

You want the metagenomics - microbiome knowledge in all the (2022.8)

4 kmiles join YiSheng group, with more strong ability of digital business, accelerate China's cross-border electricity full domain full growth

OpenCV开发中的内存管理问题

JWT学习

脑机接口003 | 马斯克称已实现与云端的虚拟自己对话,相关概念股份大涨
随机推荐
Office2021 安装MathType
【LeetCode】1374. 生成每种字符都是奇数个的字符串
遇上Mysql亿级优化,怎么办
脑机接口003 | 马斯克称已实现与云端的虚拟自己对话,相关概念股份大涨
六石管理学:入门机会只有一次,先把产品做好
MySQL安装配置教程(超级详细)
Parse common methods in the Collection interface that are overridden by subclasses
Silver circ: letter with material life insurance products should be by the insurance company is responsible for the management
MySQL安装时一直卡在starting server
Mysql安装流程 【压缩版】
Brain-computer interface 003 | Musk said that he has realized a virtual self-dialogue with the cloud, and related concept shares have risen sharply
汇编实例解析--利用tcb,tss,全局tss,ldt管理任务实现任务切换
golang刷leetcode动态规划(12)最小路径和
【LeetCode】1161. 最大层内元素和
leetcode刷题记录:7.整数反转,8.字符串转整数,9.回文数
即时通讯开发移动端网络短连接的优化手段
Kali命令ifconfig报错command not found
Five data structures of Redis and their corresponding usage scenarios
Redis集群配置
SQL server有什么认证吗?