Trapping Rain
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!
努力的刷leetcode上的题目有两个多星期了,刷了50多道,可是碰到这道题花了比较长的时间,还是没想到~伤心
然后看了下别人的博客LeetCode题目:Trapping Rain Water
学习了一下之后,自己重新写过一份代码,并且把题目思路记下来,免得以后忘记了。
主要思路:要装水的话,两边要有木板,容量以最低的木板为准。
1. 用一个数组LeftBar存左边的木板,LeftBar[i]表示 i 左边木板的最高高度,此步需要从左到右扫描数组;
2.左边的木板确定了,就要得到从右到左扫描数组得到右边的木板,扫描的同时,根据左右木板的高度从而得累加装水容量。
代码如下:
int trap(int A[], int n) {
if(A==NULL||n<=2){
return 0;
}
int trapped=0,maxBar=A[0],*leftBar=new int[n];
leftBar[0]=0;
for(int i=1;i<n;++i){
leftBar[i]=maxBar;
if(maxBar<A[i]) maxBar=A[i];
}
maxBar=A[n-1];
int left=0,right=0,container=0;
for(int i=n-2;i>0;--i){
left=leftBar[i];
right=maxBar;
container=min(left,right);
if(container>A[i]){
trapped+=container-A[i];
}
if(maxBar<A[i]) maxBar=A[i];
}
return trapped;
}