This commit is contained in:
@@ -29,6 +29,7 @@
|
||||
|
||||
# 栈与队列
|
||||
|
||||
- [总结](./stack_and_queue.md)
|
||||
- [用栈实现队列 && 用队列实现栈](./impl_stack_queue.md)
|
||||
|
||||
# 经典代码
|
||||
|
70
notes/src/stack_and_queue.md
Normal file
70
notes/src/stack_and_queue.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# 总结
|
||||
|
||||
## 栈
|
||||
|
||||
使用场景:
|
||||
|
||||
1. 需要先进后出的数据结构
|
||||
2. 匹配问题
|
||||
|
||||
经典题目:
|
||||
|
||||
[20. 有效的括号](https://leetcode.cn/problems/valid-parentheses/)
|
||||
|
||||
[1047. 删除字符串中的所有相邻重复项](https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/)
|
||||
|
||||
## 队列
|
||||
|
||||
使用场景:
|
||||
|
||||
1. 先进先出的数据结构
|
||||
2. 滑动窗口
|
||||
|
||||
### 变体:优先级队列
|
||||
|
||||
队列中的数据以 `<priority, value>` 的形式存储,每一个 `value` 都有一个 `priority` 。
|
||||
|
||||
当入队,我们根据 `priority` 将元素插入到队列的相应位置,队列中的元素总是按优先级升序或者降序排列。
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
int main(int argc, const char *argv[]) {
|
||||
// priority 为 int 类型,value 为 std::string 类型
|
||||
std::priority_queue<std::pair<int, std::string>> q;
|
||||
// 写入元素
|
||||
q.push(std::make_pair(3, "Microsoft"));
|
||||
q.push(std::make_pair(1, "Surface"));
|
||||
q.push(std::make_pair(2, "Apple"));
|
||||
q.push(std::make_pair(4, "MacBook"));
|
||||
// 访问顶部元素
|
||||
std::cout << q.top().first << q.top().second << std::endl;
|
||||
// 删除顶部元素
|
||||
q.pop();
|
||||
// 检查是否为空
|
||||
if (q.empty()) {
|
||||
std::cout << "Empty" << std::endl;
|
||||
} else {
|
||||
std::cout << "Not empty" << std::endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
```text
|
||||
4MacBook
|
||||
Not empty
|
||||
```
|
||||
|
||||
优先队列用一般用堆来实现,具有 `O(log n)` 时间复杂度的插入元素性能,`O(n)` 的初始化构造的时间复杂度。
|
||||
|
||||
经典题目:[239. 滑动窗口最大值](https://leetcode.cn/problems/sliding-window-maximum/)
|
||||
|
||||
### 变体:单调队列
|
||||
|
||||
经典题目:[239. 滑动窗口最大值](https://leetcode.cn/problems/sliding-window-maximum/)
|
Reference in New Issue
Block a user