Leetcode 42 Trapping Rain Water

本文介绍了一个算法问题:如何计算降雨后地面上能积存多少水量。通过使用双指针技术,该算法根据两边较高障碍物的高度来确定可以存储的水量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.



双指针的问题啊,重点在于,怎么判断当前能够存住水。

思考一下,存住的水取决于左右两块板的高度,首先要都大于零,并且受短板的牵制。

plank就相当于从两侧开始造一个木桶,plank的大小就是高度,只增不减,遇到比plank矮的就能储水

如果继续遇到新的plank就更新plank的值

public class Solution {
    public int trap(int[] A) {
        int i = 0, j = A.length - 1, result = 0, plank = 0;
        while(i <= j){
            plank = plank < Math.min(A[i], A[j]) ? Math.min(A[i], A[j]) : plank;
            result = A[i] >= A[j] ? result + (plank - A[j--]) : result + (plank - A[i++]);
        }
        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值