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!

思路:

找到最高的一个板子,然后从两边往中间靠近,如果高度小于当前的最大高度,结果加上当前最大高度-板子高度,否则不存水,只更新最大高度即可。

代码:

 1     int trap(int A[], int n) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         int i;
 5         int curmax, max = INT_MIN, maxIndex, result = 0;
 6         if(n == 0)
 7             return 0;
 8         for(i = 0; i < n; i++){
 9             if(A[i] > max){
10                 max = A[i];
11                 maxIndex = i;
12             }
13         }
14         curmax = A[0];
15         for(i = 1; i < maxIndex; i++){
16             if(A[i] < curmax){
17                 result += (curmax-A[i]);
18             }
19             else{
20                 curmax = A[i];
21             }
22         }
23         curmax = A[n-1];
24         for(i = n-2; i > maxIndex; i--){
25             if(A[i] < curmax){
26                 result += (curmax-A[i]);
27             }
28             else{
29                 curmax = A[i];
30             }
31         }
32         return result;
33     }
原文地址:https://www.cnblogs.com/waruzhi/p/3415266.html