刷题训练 day51 | 第十章 单调栈 part02

题目1:【二刷完成】

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        //边界判断
        if(nums == null || nums.length <= 1) {
            return new int[]{-1};
        }
        int size = nums.length;
        int[] result = new int[size];//存放结果
        Arrays.fill(result,-1);//默认全部初始化为-1
        Stack<Integer> st= new Stack<>();//栈中存放的是nums中的元素下标
        for(int i = 0; i < 2*size; i++) {
            //取模的过程遍历数组
            while(!st.empty() && nums[i % size] > nums[st.peek()]) {
                result[st.peek()] = nums[i % size];//更新result
                st.pop();//弹出栈顶
            }
            st.push(i % size);
        }
        return result;
    }
}

题目2:【二刷完成】

class Solution {
    public int trap(int[] height) {
        //单调栈方法
        int sum = 0;
        int len = height.length;
        Stack<Integer> st = new Stack<Integer>();
        st.push(0);
        for (int i=1;i<len;i++){
            if (height[i]<height[st.peek()]){
                st.push(i);
            }else if (height[i]==height[st.peek()]){
                st.pop();
                st.push(i);
            }else{
                while(!st.isEmpty() && height[i]>height[st.peek()]){
                    int mid = st.pop();
                    if (!st.isEmpty()){
                        int h = Math.min(height[i],height[st.peek()])-height[mid];
                        int w = i - st.peek() - 1;
                        int area = h*w;
                        if (area>0) sum += area;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
}

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值