一.栈与队列的API总结与回顾

1.1 类java.util.Stack的API
Deque接口及其实现提供了更完整和一致的LIFO堆栈操作集,通过Deque接口模拟栈应优先于此类。
| 方法 | 作用 | 异常 |
|---|---|---|
| new Stack<E>(); | 构造方法 | |
| boolean empty() | 堆栈是否为空 | |
| E push(E item) | item推送到此堆栈的顶部 | |
| E pop() | 出栈 | EmptyStackException |
| E peek() | 堆栈顶部的对象 | EmptyStackException |
1.2 接口java.util Interface Queue的API
| 方法 | 作用 | 异常 |
|---|---|---|
| boolean add(E e) | 添加元素 | IllegalStateException/ClassCastException /NullPointerException/IllegalArgumentException |
| boolean offer(E e) | 添加元素 | ClassCastException /NullPointerException/IllegalArgumentException |
| E remove() | 删除队列头 | NoSuchElementException |
| E poll() | 删除队列头 | |
| E element() | 返回队列头 | NoSuchElementException |
| E peek() | 返回队列头 |
1.3 接口java.util Interface Deque的API
| 方法 | 作用 | 异常 |
|---|---|---|
| boolean add(E e)/addLast(E e)t | 队尾插入 | 若超出容量限制,IllegalStateException |
| boolean offer(E e)/offerLast(E e) | 队尾插入 | 若超出容量限制,返回false,不抛异常 |
| void push(E e)/addFirst(E) | 队头插入 | 超出容量限制,抛出IllegalStateException |
| boolean offerFirst(E e) | 队头插入 | 若超出容量限制,返回false,不抛异常 |
| E getFirst() | 获取队头元素 | 若队列为空,抛出NoSuchElementException |
| E peekFirst() | 获取队头元素 | 若队列为空,返回Null |
| E getLast() | 获取队尾元素 | 若队列为空,抛出NoSuchElementException |
| E peekLast() | 获取队尾元素 | 若队列为空,返回Null |
| E pollFirst() | 删除队头元素 | deque为空,则返回 null |
| E pollLast() | 删除队尾元素 | deque为空,则返回 null |
| E removeFirst()/E pop() | 删除队头元素 | deque为空,NoSuchElementException |
| E removeLast() | 删除队尾元素 | deque为空,NoSuchElementException |
| boolean contains(Object o) | 包含指定的元素 | |
| int size() | 大小 | |
| boolean removeFirstOccurrence(Object o) | 删除指定元素的第一个出现 | |
| boolean removeLastOccurrence(Object o) | 删除指定元素的最后一次出现 | |
| Iterator descendingIterator() | 反向遍历 | |
| Iterator iterator() | 遍历队列 |
头作栈,尾作队列
1.3 java.util Class PriorityQueue的API
| 方法 | 作用 | 异常 |
|---|---|---|
| PriorityQueue(Comparator<? super E> comparator) | 构造方法 | |
| PriorityQueue(int initialCapacity) | 构造方法 | |
| PriorityQueue(int initialCapacity, Comparator<? super E> comparator) | 构造方法 | |
| boolean offer(E e)/boolean add(E e) | 添加元素 | |
| E peek() | 获取栈顶元素 | |
| boolean remove(Object o) | 删除一个指定元素 | |
| Object[] toArray()/ T[] toArray(T[] a) | 转换为数组 | |
| int size() | 队列大小 | |
| E poll() | 删除队头元素 |
难点在comparator的重写
Comparator<Student> ageComp = (s1, s2) -> s1.getAge() - s2.getAge();
Comparator<int[]> ageComp = (o1, o2)->o1[0] - o2[0])
二.相关算法总结与回顾
做栈的题目有一种玩消消乐的感觉。
2.1 消消乐
这类题目做起来有种玩消消乐的感觉
LeetCode - 20.有效的括号
LeetCode - 1047. 删除字符串中的所有相邻重复项
2.2 模拟
通过队列去模拟栈,或者通过栈来模拟队列
LeetCode - 232.用栈实现队列
LeetCode - 225. 用队列实现栈
2.3 计算器
往往通过栈来解决,很考验细节。一种是仅仅使用数值numStack就行,另外一种还需要配合操作符charStack一起解决。
LeetCode - 150. 逆波兰表达式求值
LeetCode - 227. 基本计算器 II
LeetCode - 224. 基本计算器
2.4 单调队列与优先级队列
无论是单调队列还是优先级队列都是一种高效的排序方式,相比较而言,单调队列的功能更丰富,应用也更灵活。它可以寻找距离当前元素最近/最远的最大最小值(接雨水)。
LeetCode - 347.前 K 个高频元素
LeetCode - 42. 接雨水
LeetCode - 239. 滑动窗口最大值
arrayList转int数组的方式:res.stream().mapToInt(Integer:valueOf).toArray();
参考
- jdk1.8帮助文档

被折叠的 条评论
为什么被折叠?



