队列和栈
1.栈
1.1 栈的常见操作
// 构造器
new Stack<>();
// interface
Stack.push(E item); // 返回值为item
Stack.pop(); // 返回值为stack top element
Stack.peek(); // Looks at the object at the top of this stack without removing it from the stack.返回值为 stack top object
Stack.empty(); // Tests if this stack is empty.
Stack.search(Obeject o); // the 1-based position from the top of the stack where the object is located; the return value -1 indicates that the object is not on the stack.
Stack.size(); // 返回size
// stack extends Vector java.util.Vector#isEmpty
1.2 题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
解法:
class CQueue {
// 考察点:stack
// 解题思路:
// 1.创建栈1、栈2;
// 2.appendTail操作:栈1元素先出栈入栈2,待添加元素入栈1,再将栈2所有元素出栈入栈1;
// 3.deleteHead操作:如果栈1为空则返回-1,否则栈1 pop;
// 栈和队列负负得正
// private Stack<Integer> stackFirst = new Stack<>();
// private Stack<Integer> stackSecond = new Stack<>();
// public CQueue() {
// }
// public void appendTail(int value) {
// if (stackFirst.empty()) {
// stackFirst.push(value);
// return;
// }
// while (!stackFirst.empty()) {
// stackSecond.push(stackFirst.pop());
// }
// stackFirst.push(value);
// while (!stackSecond.empty()) {
// stackFirst.push(stackSecond.pop());
// }
// }
// public int deleteHead() {
// if (stackFirst.empty()) {
// return -1;
// }
// return stackFirst.pop();
// }
private Deque<Integer> stackFirst;
private Deque<Integer> stackSecond;
public CQueue() {
stackFirst = new LinkedList<>();
stackSecond = new LinkedList<>();
}
public void appendTail(int value) {
stackFirst.push(value);
}
public int deleteHead() {
if (stackSecond.isEmpty()) {
while (!stackFirst.isEmpty()) {
stackSecond.push(stackFirst.pop());
}
}
if (stackSecond.isEmpty()) {
return -1;
}
return stackSecond.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
uploading-image-951616.png
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.提示:
各函数的调用总次数不超过 20000 次
解法:
class MinStack {
// 自己的解法
// 调用了库函数E Collections.min(Collection<E> collection)
// private Deque<Integer> minStack;
// /** initialize your data structure here. */
// public MinStack() {
// minStack = new LinkedList<>();
// }
// public void push(int x) {
// minStack.push(x);
// }
// public void pop() {
// minStack.pop();
// }
// public int top() {
// return minStack.peek();
// }
// public int min() {
// return Collections.min(minStack);
// }
// 本地考察的难点是如何实现O(1)的复杂度
// 解决思路:维护两个栈,栈B中存储栈A中所有从小到大的元素,则栈A中的最小元素始终对应栈B的栈顶元素,即min()函数只需返回栈B的栈顶元素即可。栈A每次入栈出栈同步更新栈B
private Stack<Integer> minStack;
private Stack<Integer> stack2;
/** initialize your data structure here. */
public MinStack() {
minStack = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
minStack.push(x);
if (stack2.empty() || x <= stack2.peek()) { // 这里要用<=是要避免删除重复的最小元素
stack2.push(x);
}
}
public void pop() {
if (minStack.peek().equals(stack2.peek())) { // 这里使用equals而不用==,是因为Stack用的是Integer类
stack2.pop();
}
minStack.pop();
}
public int top() {
return minStack.peek();
}
public int min() {
return stack2.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.min();
*/
1.3 单调栈
单调栈:栈里元素单调递增或单调递减的栈我们称为单调栈
1.3.1 适用问题
适用于求解数组中某个元素的下一个更大元素
1.3.2 算法模板
public int[] nextGreatElement(int[] nums) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[nums.length];
for (int i = nums.length - 1; i >= 0; i++) {
while (!stack.isEmpty() && nums[i] >= stack.peek()) { //栈非空并且nums[i]比栈顶元素大时,我们就将栈里比nums[i]小的依次出栈,这里大于等于
stack.pop();
}
res[i] = stack.isEmpty() ? -1 : stack.peek(); //
stack.push(nums[i]); // nums[i]比栈顶元素小则入栈或者更大元素nums[i]入栈
}
return res;
}
// 变形:根据题目求的问题,栈除了可以存储下一个更大元素外,也可以存储下一个更大元素的下标
public int[] nextGreatElement(int[] nums) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[nums.length];
for (int i = nums.length - 1; i >= 0; i++) {
while (!stack.isEmpty() && nums[i] >= nums[stack.peek()]) { //栈非空并且nums[i]比栈顶元素大时,我们就将栈里比nums[i]小的依次出栈
stack.pop();
}
res[i] = stack.isEmpty() ? -1 : stack.peek(); //
stack.push(i); // nums[i]比栈顶元素小则入栈或者更大元素nums[i]入栈
}
return res;
}
1.3.3 常见题目
nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。
示例 1:
输入:nums1 = [4,1,2], nums2 = [1,3,4,2].
输出:[-1,3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
- 4 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
- 1 ,用加粗斜体标识,nums2 = [1,3,4,2]。下一个更大元素是 3 。
- 2 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
示例 2:输入:nums1 = [2,4], nums2 = [1,2,3,4].
输出:[3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
- 2 ,用加粗斜体标识,nums2 = [1,2,3,4]。下一个更大元素是 3 。
- 4 ,用加粗斜体标识,nums2 = [1,2,3,4]。不存在下一个更大元素,所以答案是 -1 。
提示:
1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
nums1和nums2中所有整数 互不相同
nums1 中的所有整数同样出现在 nums2 中进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
if (nums1.length == 0 || nums2.length == 0) return nums1;
Stack<Integer> stack = new Stack<>();
int[] tmp = new int[nums2.length];
int[] res = new int[nums1.length];
for (int i = nums2.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums2[i] >= stack.peek()) {
stack.pop();
}
tmp[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(nums2[i]);
}
for (int i = 0; i < nums1.length; i++) {
res[i] = tmp[findIndex(nums2, nums1[i])];
}
return res;
}
private int findIndex(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == val) {
return i;
}
}
return -1;
}
}
优化点:上述查找nums1中每个元素对应tmp数组的结果时,我们的思路是查找出nums1中每个元素在nums2的下标,然后根据下标再返回结果。这个查找下标的时间复杂度是O(n)。因为题目说明nums2无重复元素,因此可以用hashmap存储nums2中每个元素对应下一个最大元素,然后基于nums1的每个元素作为key去查找对应value。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
if (nums1.length == 0 || nums2.length == 0) return nums1;
Stack<Integer> stack = new Stack<>();
int[] tmp = new int[nums2.length];
int[] res = new int[nums1.length];
for (int i = nums2.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums2[i] >= stack.peek()) {
stack.pop();
}
tmp[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(nums2[i]);
}
for (int i = 0; i < nums1.length; i++) {
res[i] = tmp[findIndex(nums2, nums1[i])];
}
return res;
}
private int findIndex(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == val) {
return i;
}
}
return -1;
}
}
给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素 。
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1 。
示例 1:
输入: nums = [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。
示例 2:输入: nums = [1,2,3,4,3]
输出: [2,3,4,-1,4]提示:
1 <= nums.length <= 104
-109 <= nums[i] <= 109
class Solution {
public int[] nextGreaterElements(int[] nums) {
Stack<Integer> stack = new Stack<>();
int n = nums.length;
int[] res = new int[n];
for (int i = 2 * n - 1; i >= 0; i--) {
while (!stack.isEmpty() && nums[i % n] >= stack.peek()) { // 循环队列 我们可以用 i % n求余操作来映射会原来的数组
stack.pop();
}
res[i % n] = stack.isEmpty() ? -1 : stack.peek();
stack.push(nums[i % n]);
}
return res;
}
}
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指在第 i 天之后,才会有更高的温度。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例 1:
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
示例 2:输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]
示例 3:输入: temperatures = [30,60,90]
输出: [1,1,0]提示:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[temperatures.length];
for (int i = temperatures.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && temperatures[i] >= temperatures[stack.peek()]) { // 栈里存放的是下一个更大元素的下标
stack.pop();
}
res[i] = stack.isEmpty() ? 0 : stack.peek() - i;
stack.push(i);
}
return res;
}
}
2.队列
Deque<Integer> stackFirst = new LinkedList<>();
2.1 队列常见操作
// 构造器
Queue<Integer> queue = new LinkedList<>();
// 添加
boolean add(E e); // 当队列满时,add会抛出IllegalStateException异常
boolean offer(E e); // 当队列满时,只会返回false
// 查询队头元素
E peek();
// 队头出队
E poll(); // 当队列空时,返回null
E remove(); // 当队列空时,抛NoSuchElementException异常
2.2 栈实现队列
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。示例:
输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False提示:
1 <= x <= 9
最多调用100 次 push、pop、top 和 empty
每次调用 pop 和 top 都保证栈不为空
class MyStack {
private Queue<Integer> queue;
private int topElement;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
topElement = x;
}
public int pop() {
int size = queue.size();
while (size > 2) {
queue.offer(queue.poll());
size--;
}
topElement = queue.peek(); // 更新队头元素
queue.offer(queue.poll());
return queue.poll();
}
public int top() {
return topElement;
}
public boolean empty() {
return queue.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/