单调栈
概念:
单调栈是一种特殊的栈,单调栈中的元素保持单调递增或单调递减。
使用场景:
通常在一个一维数组中,要寻找任意一个元素的左边或右边第一个比它大或小的元素位置
本质:
就是空间换时间,将遍历过的元素放到单调栈中
具体题目:
思路一:循环
因为要遍历两次数组,所以最后会超时
public class Solution739 {
public int[] dailyTemperatures(int[] temperatures) {
int[] answer = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++) {
for (int j = i + 1; j < temperatures.length; j++) {
if (temperatures[j] > temperatures[i]) {
answer[i] = j - i;
break;
}
if (j == temperatures.length - 1) {
answer[i] = 0;
}
}
}
return answer;
}
}
思路二:单调栈
首先需要定义一个栈来模拟单调栈,每当我们遍历一个元素时,去和栈顶的元素进行比较,如果当前元素大于栈顶元素,那么当前元素对于栈顶元素来说,就是一个比它大的元素,将栈顶元素弹出,继续判断下一个栈顶,直到栈为空或者当前元素小于栈顶元素,将当前元素加入到栈中。使用单调栈只需要遍历一次数组。
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] answer = new int[temperatures.length];
Stack<Integer> stack = new Stack<>();
stack.add(0);
for (int i = 1; i < temperatures.length; i++) {
if (temperatures[i] > temperatures[stack.peek()]) {
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
int temp = stack.pop();
answer[temp] = i - temp;
}
stack.add(i);
} else if (temperatures[i] < temperatures[stack.peek()]) {
stack.add(i);
} else if (temperatures[i] == temperatures[stack.peek()]) {
stack.add(i);
}
}
return answer;
}
}
class Solution {
public int trap(int[] height) {
int res = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
int curr = stack.pop();
int right = i;
if (!stack.isEmpty()) {
int left = stack.peek();
int tall = Math.max((Math.min(height[right], height[left]) - height[curr]), 0);
int width = right - left - 1;
res += tall * width;
}
}
if (!stack.isEmpty() && height[i] == height[stack.peek()]) {
stack.pop();
}
stack.add(i);
}
return res;
}
}