题目地址
https://leetcode-cn.com/problems/trapping-rain-water/
题目描述
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
Constraints:
- n == height.length
- 0 <= n <= 3 * 10^4
- 0 <= height[i] <= 10^5
思路
对每个柱子上的积水,由其左右两边最高的柱子中较矮的柱子决定,因此可以计算每个柱子左右最高的柱子,然后计算其中矮的柱子和当前柱子的差。
题解
class Solution {
public int trap(int[] height) {
int res=0,i,j;
int len = height.length;
int[] left = new int[len];
int[] right = new int[len];
int lmax=0;
for(i=0;i< height.length;++i){
left[i]=lmax;
lmax = Math.max(lmax,height[i]);
}
int rmax = 0;
for(j= height.length-1;j>=0;--j){
right[j]=rmax;
rmax = Math.max(rmax,height[j]);
}
for(i=0;i<len;i++){
int h = Math.min(left[i],right[i]);
if(h>height[i]) res+= h - height[i];
}
return res;
}
}