首页 > 其他分享 >42. Trapping Rain Water

42. Trapping Rain Water

时间:2022-11-06 20:35:33浏览次数:40  
标签:lower Trapping level int res 42 height Water

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

public int trap(int[] height) {
int l = 0,
r = height.length - 1,
level = 0,
res = 0,
lower = 0;
while (l < r) {
if (height[l] < height[r]) {
lower = height[l];
l++;
} else {
lower = height[r];
r--;
}
level = Math.max(level, lower);
res += level - lower;
}
return res;
}






标签:lower,Trapping,level,int,res,42,height,Water
From: https://www.cnblogs.com/MarkLeeBYR/p/16863808.html

相关文章