单调栈(单调递增栈)

文章介绍了两种使用Java编程解决经典算法问题的方法:一是用单调栈优化解每日温度问题,避免了暴力解法的超时;二是应用单调栈解决接雨水问题,有效地计算容器能接住的雨水量。这两种方法都展示了在处理数组数据时,单调栈作为优化工具的有效性。
摘要由CSDN通过智能技术生成

1、每日温度(lc739): 

暴力解法(顺序暴力会超时)

      public int [] dailyTemperatures1(int[] temperatures){
        int n = temperatures.length;
        int [] ans = new int[n];
        Arrays.fill(ans,0);
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                if (temperatures[i] < temperatures[j]) {
                    ans[i] = j-i;
                }
                break;
            }
        }
        return ans;
    }

单调栈 解法:

public int[] dailyTemperatures(int[] temperatures){
        //单调栈其实就是加入已经遍历过的元素
        int len = temperatures.length;
        int[] ans = new int[len];//初始元素就是0
        Stack<Integer> stack = new Stack<>();
        stack.push(0);//先将第一个元素推入
        for (int i = 1; i < len; i++) {
            if (temperatures[i] < temperatures[stack.peek()]) {
                stack.push(i);
            }//小于等于栈口元素则加入到栈中
            if (temperatures[i] == temperatures[stack.peek()]) {
                stack.push(i);
            }else{
                while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
                    ans[stack.peek()] = i - stack.peek();
                    stack.pop();
                }
                stack.push(i);
            }
        }
        return ans;
    }

2、接雨水:

单调栈解法:

{
        public int trap(int[] height) {
            int len = height.length;
            if (len < 3)   return 0;
            int ans = 0;
            Stack<Integer> stack = new Stack<>();
            stack.push(0);
            for (int i = 1; i < len; i++) {
                if (height[i] < height[stack.peek()]) {
                    stack.push(i);
                }
                if (height[i] == height[stack.peek()]){
                    stack.pop();
                    stack.push(i);
                }else {
                    while (!stack.isEmpty() && height[i] > height[stack.peek()]){
                        int mid = stack.peek();
                        stack.pop();
                        if (!stack.isEmpty()) {
                            int h = Math.min(height[i],height[stack.peek()])-height[mid];
                            int w = i - stack.peek() - 1;
                            ans += h*w;
                        }
                    }
                    stack.push(i);
                }
            }
            return ans;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值