【Hot100】LeetCode—42. 接雨水



1- 思路

单调栈

  • 目标——> 求右侧第一个比当前元素大的元素 ——> 单调递增栈

2- 实现

⭐接雨水——题解思路

在这里插入图片描述

class Solution {
    public int trap(int[] height) {
        if(height.length == 0){
            return 0;
        }

        int sum = 0;
        Stack<Integer> st = new Stack<>();
        st.push(0);
        for(int i = 1 ; i < height.length;i++){
            if(height[i] <= height[st.peek()]){
                st.push(i);
            }else{
                while(!st.isEmpty() && height[i] > height[st.peek()]){
                    int right = i;
                    int mid = st.peek();
                    st.pop();
                    if(!st.isEmpty()){
                        int left = st.peek();
                        int h = Math.min(height[left],height[right])-height[mid];
                        int width = right-left-1;
                        int nowArea = h*width;
                        sum+=nowArea;
                    }
                }
                st.push(i);
            }
        }
        return sum;
    }
}

3- ACM 实现

public class trap {

    public static int trap(int[] nums){
        Stack<Integer> st = new Stack<>();
        int res = 0;
        // 遍历
        st.push(0);
        for(int i = 1 ; i <nums.length;i++){
            if(nums[i]<=nums[st.peek()]){
                st.push(i);
            }else{
                while (!st.isEmpty() && nums[i] > nums[st.peek()]){
                    int right = i;
                    int mid = st.peek();
                    st.pop();
                    if(!st.isEmpty()){
                        int left = st.peek();
                        int h = Math.min(nums[left],nums[right])-nums[mid];
                        int width = right-left-1;
                        int nowArea = width*h;
                        res+=nowArea;
                    }
                }
                st.push(i);
            }
        }
        return res;
    }

    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数组长度");
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0 ; i < n ;i++){
            nums[i] = sc.nextInt();
        }
        System.out.println("结果是"+trap(nums));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值