您的位置:首页 > 移动开发

第一周:[leetcode] 42. Trapping Rain Water

2017-02-26 11:34 369 查看
题目链接:链接

question: 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.

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.



简而言之,该题是计算非负数组形成的凹槽所能承载的水量;

通过观察得知,数组的载水量由两值形成的局部(凹槽)的最低点决定,因此,计算总在水量应是从数组局部较低点向较高点扫描。将整个数组视为整体,维护left=0和right=height.size()-1两个index,通过比较取较小值向高点移动,直到left == right停止,计算累计在水量。

c++实现如下:

int trap(vector<int>& height) {
int front = 0;
int back = height.size()-1;
int res = 0;
while(front < back){
//取两者较小值向高点移动
if(height[front] < height[back]){
int f = height[front];
while(height[front] <= f && front < back){
res += f - height[front];
front++;
}
}
else{
int b = height[back];
while(height[back] <= b && front < back){
res += b - height[back];
back--;
}
}
}
return res;
}


通过学习solution,发现更加简便的计算方法:

维护level,从第0层开始由两边向中扫描,累积在水量。直至l

int trap(vector<int>& height) {
int l = 0, r = height.size()-1, level = 0, water = 0;
while (l < r) {
int lower = height[height[l] < height[r] ? l++ : r--];
level = max(level, lower);
water += level - lower;
}
return water;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode