算法与数据结构基础 - 队列(Queue)
2024-09-01 01:45:41
队列基础
队列具有“先进先出”的特点,用这个特点我们可以用它来处理时间序列相关或先后次序相关的问题,例如 LeetCode题目 933. Number of Recent Calls,时间复杂度O(1):
//933. Number of Recent Calls
private queue<int> q;
public int ping(int t) {
q.push(t);
while(q.front()<t-) q.pop();
return q.size();
}
尝试用queue求解这样一个问题:假设某服务对单个IP限制访问1000次/min,输入为ip、TimeStamp;返回为bool,超过限制返回false,否则返回true。
相关LeetCode题:
933. Number of Recent Calls 题解
346. Moving Average from Data Stream 题解
队列应用于BFS
也常常应用队列先进先出的特性,模拟广度优先搜索(BFS)过程,例如 LeetCode题目 582. Kill Process,时间复杂度O(n):
//582. Kill Process
class Solution {
public:
vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
vector<int> res;
unordered_map<int,unordered_set<int>> m;
for(int i=;i<pid.size();i++) m[ppid[i]].insert(pid[i]);
queue<int> q;
q.push(kill);
while(!q.empty()){
int p=q.front();q.pop();
res.push_back(p);
for(auto child:m[p]) q.push(child);
}
return res;
}
};
相关LeetCode题:
deque双端队列
相比queue支持前端删除、尾端插入,deque支持前端插入/删除、尾端插入/删除,如果前端和尾端都需要插入/删除,则应选用双端队列deque。
相关LeetCode题:
862. Shortest Subarray with Sum at Least K 题解
最新文章
- sqlservr (708) 打开日志文件 C:\Windows\system32\LogFiles\Sum\Api.log 时出现错误 -1032 (0xfffffbf8)
- ie6-ie8中不支持opacity透明度的解决方法
- Android学习笔记(六)
- 七、Block 封装代码
- SQL server 表中如何创建索引?
- Oracle使用%type类型的变量输出结果
- JavaScipt call和apply用法
- 1021: [SHOI2008]Debt 循环的债务 - BZOJ
- 测来测去,感觉REQUESTS最实在
- mysql中的timestamp类型时间比较:unix_timestamp函数
- 通过ComponentName获取相应的Widget
- 【HDOJ】1243 反恐训练营
- 基于.NET MVC的高性能IOC插件化架构(一)
- SQL语句中的乘号
- eclipse - tomcat 远程调试
- gdb篇
- jqueryUI中datepicker的使用,解决与asp.net中的UpdatePanel联合使用时的失效问题
- Reorder List [leetcode] 这两种思路
- NOIP2010-普及组复赛-第四题-三国游戏
- java第六周作业
热门文章
- 得知OpenCV研究报告指出系列(一)VS2010+OpenCV2.4.9环境配置
- sql service 游标和触发器的使用
- WPF生命周期
- 将RDL报表转换成RDLC报表的函数
- 自定义LISTBOX内子项为checkbox或者radio时,关于IsChecked绑定
- extjs grid 复选框选择事件
- 变量的选择——Lasso&;Ridge&;ElasticNet
- postgresql + JDBC 学习
- Setting up multi nodes live migration in Openstack Juno with devstack
- Z Order of Controls in Delphi FireMonkey(Tom Yu的博客)