单调栈的使用

单调栈

概念:

​ 单调栈是一种特殊的栈,单调栈中的元素保持单调递增或单调递减。

使用场景:

​ 通常在一个一维数组中,要寻找任意一个元素的左边或右边第一个比它大或小的元素位置

本质:

​ 就是空间换时间,将遍历过的元素放到单调栈中

具体题目:

思路一:循环

因为要遍历两次数组,所以最后会超时

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迪迦敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值