队列基础

队列具有“先进先出”的特点,用这个特点我们可以用它来处理时间序列相关或先后次序相关的问题,例如 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  题解

622. Design Circular Queue  题解

队列应用于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题:

582. Kill Process  题解

deque双端队列

相比queue支持前端删除、尾端插入,deque支持前端插入/删除、尾端插入/删除,如果前端和尾端都需要插入/删除,则应选用双端队列deque。

相关LeetCode题:

641. Design Circular Deque  题解

862. Shortest Subarray with Sum at Least K  题解

353. Design Snake Game  题解

最新文章

  1. sqlservr (708) 打开日志文件 C:\Windows\system32\LogFiles\Sum\Api.log 时出现错误 -1032 (0xfffffbf8)
  2. ie6-ie8中不支持opacity透明度的解决方法
  3. Android学习笔记(六)
  4. 七、Block 封装代码
  5. SQL server 表中如何创建索引?
  6. Oracle使用%type类型的变量输出结果
  7. JavaScipt call和apply用法
  8. 1021: [SHOI2008]Debt 循环的债务 - BZOJ
  9. 测来测去,感觉REQUESTS最实在
  10. mysql中的timestamp类型时间比较:unix_timestamp函数
  11. 通过ComponentName获取相应的Widget
  12. 【HDOJ】1243 反恐训练营
  13. 基于.NET MVC的高性能IOC插件化架构(一)
  14. SQL语句中的乘号
  15. eclipse - tomcat 远程调试
  16. gdb篇
  17. jqueryUI中datepicker的使用,解决与asp.net中的UpdatePanel联合使用时的失效问题
  18. Reorder List [leetcode] 这两种思路
  19. NOIP2010-普及组复赛-第四题-三国游戏
  20. java第六周作业

热门文章

  1. 得知OpenCV研究报告指出系列(一)VS2010+OpenCV2.4.9环境配置
  2. sql service 游标和触发器的使用
  3. WPF生命周期
  4. 将RDL报表转换成RDLC报表的函数
  5. 自定义LISTBOX内子项为checkbox或者radio时,关于IsChecked绑定
  6. extjs grid 复选框选择事件
  7. 变量的选择——Lasso&amp;Ridge&amp;ElasticNet
  8. postgresql + JDBC 学习
  9. Setting up multi nodes live migration in Openstack Juno with devstack
  10. Z Order of Controls in Delphi FireMonkey(Tom Yu的博客)