Trapping Rain Water
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!
思路:这道题先找出中间最高的柱子,记下位置maxIndex。然后分别从两边开始向中间循环遍历。先从左边开始记下前一个的柱子高度sum1,然后与后一个的柱子高度相比较,如果比后面的高,则他们两的差额累加到water,反之,更新sum1。再者,从右边开始,相同思路。这样就可以计算出最后储水量。
class Solution { public: int trap(int A[], int n) { if(n<2) return 0; int max=A[0]; int maxIndex=0; for(int i=1;i<n;i++) { if(A[i]>max) { max=A[i]; maxIndex=i; } } int water=0; int sum1=0; for(int i=0;i<maxIndex;i++) { if(sum1>A[i]) { water+=sum1-A[i]; } else sum1=A[i]; } int sum2=0; for(int i=n-1;i>maxIndex;i--) { if(sum2>A[i]) { water+=sum2-A[i]; } else sum2=A[i]; } return water; } };