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
题目链接:https://leetcode-cn.com/problems/trapping-rain-water/
思路
接雨水的量取决于较矮一边的高度,因此总体思路是,先找到最高的地方,再在其两侧取与较矮一边决定的能收纳的水量。
class Solution {
public:
int trap(vector<int>& height) {
int len = height.size();
if(len==0) return 0;
int last = height[0], res = 0, imax = 0, hmax = height[0];
for(int i=0; i<len; ++i){
if(hmax<height[i]){
imax = i;
hmax = height[i];
}
}
for(int i=1; i<imax; ++i){
if(height[i]<last){
res += (last-height[i]);
}else{
last = height[i];
}
}
last = height[len-1];
for(int i=len-1; i>imax; --i){
if(height[i]<last){
res += (last-height[i]);
}else{
last = height[i];
}
}
return res;
}
};

本文详细解析了LeetCode上的经典问题——接雨水(Trapping Rain Water)。通过寻找最高柱子,从两边向中间遍历,利用栈、双指针等算法技巧,计算出雨水中能被保留的总量。该问题考验了数据结构和算法的理解,适用于准备编程面试和技术提升。

874

被折叠的 条评论
为什么被折叠?



