文章目录
LeetCode精选题之栈和队列
参考资料:
CyC2018的LeetCode题解
liuyubobobo的LeetCode课程
总结:
- 栈的特点是先进后出,队列的特点是先进先出,根据它们的特点能实现栈和队列的相互转化。
- 递归的本质就是计算机使用系统栈来实现的,所以二叉树的前序、后序、中序遍历能使用栈来实现。
- 对于BFS即广度优先遍历需要使用队列来实现,因为对于距离近的节点加入容器之后要先被访问,这就是先进先出的特点。BFS包括二叉树的BFS和图的BFS,二者的区别是二叉树只有一个起始点,图可以有多个起始点,所以图的BFS相关的题目要维护一个isVisited布尔数组,来标识某个节点是否已经被访问过。
- 队列中有一个优先队列,在Java中是PriorityQueue类,其默认是小顶堆,底层实现是堆的结构。对于求第k大或者第k小元素的题目较为适用,因为相当于对加入队列的元素进行了排序。其复杂度是
O(nlogk)
,当k远小于n时,这个复杂度是优于O(nlogn)
的。创建PriorityQueue对象时可以定制比较器,比如根据元素在原数组中出现的次数进行排列,这样排序的规则就比较灵活。
1 用栈实现队列–LeetCode232
使用栈实现队列的下列操作:
- push(x) – 将一个元素放入队列的尾部。
- pop() – 从队列首部移除元素。
- peek() – 返回队列首部的元素。
- empty() – 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
- 你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
- 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
- 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
思路:栈的顺序为后进先出,而队列的顺序为先进先出。使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。
import java.util.Stack;
class MyQueue {
private Stack<Integer> stack1;//存数据
private Stack<Integer> stack2;//取数据
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (!stack2.empty()) {
return stack2.pop();
}
//如果stack2为空,则将stack1中的全部元素放到stack2中
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
/** Get the front element. */
public int peek() {
if (!stack2.empty()) {
return stack2.peek();
}
//如果stack2为空,则将stack1中的全部元素放到stack2中
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack1.empty() && stack2.empty();
}
}
2 用队列实现栈–LeetCode225
使用队列实现栈的下列操作:
- push(x) – 元素 x 入栈
- pop() – 移除栈顶元素
- top() – 获取栈顶元素
- empty() – 返回栈是否为空
注意:
- 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
- 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
- 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
思路:在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。
import java.util.Queue;
import java.util.LinkedList;
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
int cnt = queue.size();
while (cnt-- > 1) {
queue.offer(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
3 最小栈–LeetCode155
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) —— 将元素 x 推入栈中。
- pop() —— 删除栈顶的元素。
- top() —— 获取栈顶元素。
- getMin() —— 检索栈中的最小元素。
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:pop、top 和 getMin 操作总是在 非空栈 上调用。
class MinStack {
private Stack<Integer> saveStack;
private Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
saveStack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
saveStack.push(x);
if (minStack.empty()) {
minStack.push(x);
return;
}
if (x < minStack.peek()) {
minStack.push(x);
}else {
minStack.push(minStack.peek());
}
}
public void pop() {
saveStack.pop();
minStack.pop();
}
public int top() {
return saveStack.peek();
}
public int getMin() {
return minStack.peek();
}
}
4 用栈实现括号匹配–LeetCode20
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
代码如下:
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
if (s == null) {
return true;//空字符串是有效字符串
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (stack.empty()) {
stack.push(s.charAt(i));
continue;
}
Character peekChar = stack.peek();
if (peekChar=='(' && s.charAt(i)==')'
|| peekChar=='[' && s.charAt(i)==']'
|| peekChar=='{' && s.charAt(i)=='}') {
stack.pop();
}else {
stack.push(s.charAt(i));
}
}
return stack.empty();
}
}
5 每日温度–LeetCode739
根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
,你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]
。
提示:气温 列表长度的范围是 [1, 30000]
。每个气温的值的均为华氏度,都是在 [30, 100]
范围内的整数。
思路:在遍历数组时用栈把数组中的数存起来,如果当前遍历的数比栈顶元素来的大,说明栈顶元素的下一个比它大的数就是当前元素。
class Solution {
public int[] dailyTemperatures(int[] T) {
Stack<Integer> stack = new Stack<>();
int n = T.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
while (!stack.empty() && T[i] > T[stack.peek()]) {
int prev = stack.pop();
res[prev] = i - prev;
}
stack.push(i);
}
return res;
}
}
6 下一个更大元素II–LeetCode503
给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例 1:
输入: [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
注意: 输入数组的长度不会超过 10000。
与上一题不同的是,这里数组是循环数组,并且最后要求的不是距离而是下一个元素。
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> stack = new Stack<>();
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res, -1);
int time = 2;
while (time-- > 0) {//遍历两次数组,目的是让最后一个元素找到下一个更大元素
for (int i = 0; i < n; i++) {
while (!stack.empty() && nums[i] > nums[stack.peek()]) {
int prev = stack.pop();
res[prev] = nums[i];
}
stack.push(i);
}
}
return res;
}
}
7 二叉树的层序遍历–LeetCode102
给你一个二叉树,请你返回其按层序遍历得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
代码如下:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int levelSize = 1;
while (!queue.isEmpty()) {
int cnt = 0;
List<Integer> tempList = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
tempList.add(node.val);
if (node.left != null) {
cnt++;
queue.offer(node.left);
}
if (node.right != null) {
cnt++;
queue.offer(node.right);
}
}
levelSize = cnt;
res.add(tempList);
}
return res;
}
}
8 前K个高频元素–LeetCode347
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
- 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
- 你可以按任意顺序返回答案。
思路:首先使用Map统计频次,然后根据频次将数组加入到优先队列中(注意优先队列的比较器),优先队列的容量不超过k
,最后取出优先队列的k个元素放入数组中输出。
时间复杂度:O(n log k)
,优于O(n log n)
注意题目中保证了k
的有效性,所以在代码中没有做判断。
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], 1);
}else {
map.put(nums[i], 1+map.get(nums[i]));
}
}
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {//定制比较器,按照在map中的频次来比较,这里为小顶堆
public int compare(Integer a , Integer b) {
return map.get(a) - map.get(b);
}
});
for (Integer num : map.keySet()) {
if (pq.size() >= k) {
if (map.get(pq.peek()) < map.get(num)) {// 这里注意是比较频次,我一开始直接比较值了
pq.poll();
pq.offer(num);
}
}else {
pq.offer(num);
}
}
int[] res = new int[k];
int index = 0;
while (!pq.isEmpty()) {
res[index++] = pq.poll();
}
return res;
}
}