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 static int Trap(int[] height)
{
int result = 0;
int max_y = 0;
for (int i = 0; i < height.Length; i++)
{
int cur = height[i];
if (cur > 0)
{
if (max_y > 0)
{
int full_level = (cur < max_y) ? cur : max_y;
for (int j = i - 1; j > 0; j--)
{
if (full_level > height[j])
{
result += full_level - height[j];
height[j] = full_level;
}
else
{
break;
}
}
}
if (cur > max_y)
{
max_y = cur;
}
}
}
return result;
}
过程示意图如下:
我在网站的解题思路介绍里面看到了一个更加简洁的方法,示意图如下
用c#重写一下,没有提交验证,仅供参考:
public static int Trap_s(int[] height)
{
int ans = 0;
int left = 0, right = height.Length - 1;
int left_max = height[left], right_max = height[right];
while (left < right)
{
if (height[left] < height[right])
{
if (left_max <= height[left])
{
left_max = height[left];
}
else
{
ans += left_max - height[left];
}
left++;
}
else
{
if (right_max <= height[right])
{
right_max = height[right];
}
else
{
ans += right_max - height[right];
}
right--;
}
}
return ans;
}