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
.
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!
solution:原本的算法是找出当前点的左右最大值,取最小,减去当前的高度,即得到当前点的容水量,不过需要两个数组来存左右最大值,在论坛上看到一个非常巧妙的算法没有额外空间:其核心还是一样,但是关键之处是按照数组的最大值将输入数组划分成两部分,左边部分小于最大值,右边也是,左边部分循环时就可以不用比较左右的最小值了,只需要不停保存左最大值即可,因为右边存在最大值了;同理引申到右半部分。
需要注意的一点是边界的时候最大值为0.
class Solution {
public:
int trap(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(A == NULL || n <= 1)
return 0;
int res = 0;
int maxIndex = 0;
for(int i = 0; i < n; i++)
{
if(A[i] > A[maxIndex])
maxIndex = i;
}
int leftMax = 0;
for(int i = 0; i < maxIndex; i++)
{
if(leftMax > A[i])
res += leftMax-A[i];
else
leftMax = A[i];
}
int rightMax = 0;
for(int i = n-1; i > maxIndex; i--)
{
if(rightMax > A[i])
res += rightMax-A[i];
else
rightMax = A[i];
}
return res;
}
};