题目描述:
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
给定一个高度数组height[],每个元素表示高度为height[i]的挡板,它们之间的间隔形成积水,求最大积水量。例如高度为1,0,2的挡板,积水量为1。
思路:
1. 一次遍历,求出每个挡板的左右最大的高度
2. 再次遍历height[],取它左右最大高度的最小值,减去height[i],就是它的积水量。累加所有挡板的积水量。
实现代码:public int Trap(int[] height)
{
if(height == null || height.Length < 3)
{
return 0;
}
var len = height.Length;
int[] left = new int[len];
int[] right = new int[len];
left[0] = height[0];
right[len-1] = height[len-1];
for(int i=1; i< len; i++){
left[i] = Math.Max(left[i-1], height[i]);
right[len - i - 1] = Math.Max(right[len - i], height[len - i - 1]);
}
int sum = 0;
for(int i=1; i<len-1; i++){
sum += Math.Min(left[i], right[i]) - height[i];
}
return sum;
}