leetcode-42 Trapping Rain Water

本文介绍了一种使用双指针法解决雨后积水计算问题的方法。通过遍历数组两端并向中间移动,利用已知的最高点来计算每个位置能容纳多少雨水。此算法的时间复杂度为O(n),适用于LeetCode中的特定题目。

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

问题描述:

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

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


The above elevation map is represented by array[0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section)are being trapped. Thanks Marcos for contributing this image!

 

问题分析:

同样也是双指针法解决问题,类似的问题有:《leetcode-11 Container With Most Water》

找到左右边界,然后逐步向里逼近;时间复杂度O(n)

 

代码:

public class Solution {
   public int trap(int[] A) {
        // 双指针法,记录左右指针位置
        int left = 0, right = A.length - 1;
        int result = 0;
        // 记录左右边界的最高高度
        int maxLeft = 0, maxRight = 0;
       
        while (left <= right) {
            // 由于水桶效应,故与left,right较小值相关
            if (maxLeft <= maxRight) {
                if (A[left] > maxLeft)
                    maxLeft = A[left];
                else
                    result += (maxLeft -A[left]);
                left++;
            } else {
                if (A[right] > maxRight)
                    maxRight = A[right];
                else
                    result += (maxRight -A[right]);
                right--;
            }
        }
        return result;
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值