42:接雨水

42.接雨水

https://leetcode.cn/problems/trapping-rain-water/submissions/

单调栈

class Solution {
    public int trap(int[] height) {
        Stack<Integer> temp = new Stack<Integer>();
       int size = height.length;
        if(size <= 2){
            return 0;
        }
        int sum = 0;
        temp.push(0);

        for(int i=1;i<size;i++){
            int StackTop = temp.peek();
            if(height[StackTop] > height[i]){
                temp.push(i);
            }else if(height[StackTop] == height[i]){
                temp.pop();
                temp.push(i);
            }else{
                
                while(!temp.isEmpty()&& height[StackTop] < height[i]){
                    int mid = temp.pop();
                    if(!temp.isEmpty()){
                        int left = temp.peek();
                        int h = Math.min(height[left],height[i])-height[mid];
                        int w = i-left-1;
                        int hold = h * w;
                        if (hold > 0) sum += hold;
                        StackTop = temp.peek();
            
                    }
                }
                temp.push(i);
            }
        }
                return sum;
    }
}

动态规划:按照列来计算,宽度设为1,求高度差。

雨水面积:min(左边柱子的最高高度,记录右边柱子的最高高度) - 当前柱子高度。

从左向右遍历:maxLeft[i] = Math.max(height[i], maxLeft[i - 1])

从右向左遍历:maxRight[i] = Math.max(height[i], maxRight[i + 1])

时间复杂度为O(n^2)。 空间复杂度为O(1)

class Solution {
    public int trap(int[] height) {
        int size =height.length;
        int sum =0;
        int[] leftMax = new int[size];
        int[] rightMax = new int[size];

        leftMax[0] = height[0];
        for(int i=1;i<size;i++){
            leftMax[i] = Math.max(leftMax[i-1],height[i]);
        } 
        rightMax[size-1]=height[size-1];
        for(int i=size-2;i>=0;i--){
            rightMax[i] = Math.max(rightMax[i+1],height[i]);
        }
        
        for(int i=0;i<size;i++){
            int count = Math.min(leftMax[i],rightMax[i])-height[i];
            if(count >0)sum+=count;
        }
return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值