Leetcode 42. Trapping Rain Water

本文深入解析了一种计算雨水在地形中蓄积量的高效算法。通过对比两端的地形高度,逐步逼近并累计蓄水量,实现了O(n)的时间复杂度。文章详细介绍了算法思路与实现代码。

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

Problem:

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.


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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Solution:

  此题和Leetcode 11非常相似,先回顾一下Leetcode 11,它要求我们找到在两个柱子中间最大的蓄水量,因此我们就从两端开始不断靠近,靠近原则是短的那边靠近,因为只有短的那边变长才有超过当前最大蓄水量的可能性,长的那边靠近必然是蓄水量越来越少。相似的来看看这道题,left和right分别初始化为最左侧和最右侧,也是短的那边向长的那边靠近,不同的是,在找到比短的那边长的边之前需要不断累加蓄水量。算法时间复杂度为O(n)。

Code:

 

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         int result = 0;
 5         int left = 0;
 6         int right = height.size()-1;
 7         while(left < right){
 8             int minimal = min(height[left],height[right]);
 9             if(minimal == height[left]){
10                 left++;
11                 while(height[left] < minimal){
12                     result += (minimal-height[left]);
13                     left++;
14                 }
15             }
16             else{
17                 right--;
18                 while(height[right] < minimal){
19                     result += (minimal-height[right]);
20                     right--;
21                 }
22             }
23         }
24         return result;
25     }
26 };

 

转载于:https://www.cnblogs.com/haoweizh/p/10229442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值