Skip to main content

42 Trapping Rain Water

Leetcode

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

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) 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.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9


可以遍历两次,第一次从左到右,记录当前最高高度,假设未来会遇到更高的或一样高的,记录未来遇到更高或一样高的产生的体积。遇到更高的或一样高的,就把记录的体积加上,并更新最高高度,以计算下一个体积。从左到右遍历后,记录了所有两边一样高或右边更高的容器的体积,然后再从右到左遍历,用类似的方法计算左边较高容器的体积,两边一样高的已经计算过,不需要重复计算。

public int trap(int[] height) {
int total=0;
int len=height.length;
int pre=height[0];
int left=0, right=0;
for(int i=1;i<len;++i){
int cur=height[i];
if(cur>=pre){
total+=left;
left=0;
pre=cur;
} else {
left+=pre-cur;
}
}
pre=height[len-1];
for(int i=len-2;i>=0;--i){
int cur=height[i];
if(cur>pre){
total+=right;
right=0;
pre=cur;
} else {
right+=pre-cur;
}
}
return total;
}