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

leetcode question 42: Trapping Rain Water

2018-03-14 16:30 302 查看
问题:
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. 
分析:        这道题很有意思,十分接近生活,大意是说数组表示的相当是墙的高度,问这片墙可以围起多少水。        我一开始的想法是想看高度为1这一层,根据为空的格子的数目来确认第一层可以装多少水,再看第二层……如此类推,个人认为思路是没错的,但是写好代码之后运行却发现报了超时的错误。查看之后发现是因为Check的数组里面有一个是包含了两万多个数字,最高又是3万多层,这样算下来我的计算量级就达到了10^12次方,太大了……因此不可行。        后来通过上网查阅资料,受到TonyYPZhang的启发,学习到一种更为简便的方法,如下:
        1.只要求出一个位置左边和右边的最大值,就可以判断该位置的最高水位是两个最大值的最小值,再减去该位置的原本高度,就可以知道该位置上面的水有多少了。
        2.知道这个之后,我们只要先从最左和最右两个位置开始,那左边最大和右边最大就分别是这两个位置的值。然后往中间迭代,每次计算左边最大和右边最大的较小值的那一边的值。(有点难解释,但是代码十分好懂,而且简单快捷)不得不说这是一个好方法。
        下面是代码:
class Solution {
public:
int trap(vector<int>& height) {
int sum = 0;
int left = 0 , right = height.size() - 1;
int leftMax = 0 ,rightMax = 0 ;//左边最大和右边最大

while( left < right ){
leftMax = max( leftMax , height[left] );
rightMax = max( rightMax , height[right] );

if( leftMax < rightMax ){//选左边最大和右边最大中较小的那一边
sum += leftMax - height[left];
left ++;
}else {
sum += rightMax - height[right];
right --;
}
}
return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法