题目如下:
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!
解题方面,从前到后遍历,判断左右高度后累增水的数量,这个数量应该要是较低一边的数量(较高的减去较小的),并且坐标有相应的增大/减小。设置的两个坐标一个从最左边开始一个从最右边开始,依据前面的规则向中间靠拢。当左边坐标不再小于右边完成。代码如下:
int trap(vector<int>& height) {
int result = 0;
int i = 0, k = height.size() - 1;
int h;
while (i < k) {
if (height[i] < height[k]) {
h = height[i++];
while (i < k && height[i] <= h) {
result += h - height[i];
i++;
}
}
else {
h = height[k--];
while (i < k && height[k] <= h) {
result += h - height[k];
k--;
}
}
}
return result;
}