Trapping Rain Water

解析参照:http://www.xuebuyuan.com/1586534.html

开始被那个给图的骗了,以为只要下降上升就可以,而其实中间的某些局部最高点,并不能觉得整个雨水高度。

最后还是两个指针向中间遍历,每次移动较小的,而当前最大的不动。计算面积要使用当前第二高的线。

 1 class Solution {
 2 public:
 3     int Min(int a,int b)
 4     {
 5         return a>b?b:a;
 6     }11     int trap(vector<int>& height) {
12         int len = height.size();
13 
14         if(len<=2)
15            return 0;
16         int secondHeight = 0;
17         int i=0,j=len-1,area=0;20         while(i!=j)
21         {
22            if(height[j]>secondHeight && height[i]>secondHeight)
23            {
24                secondHeight = Min(height[i],height[j]);
25            }
26 
27            if(height[i]>height[j])
28            {
29                if(height[j]<secondHeight)
30                area += secondHeight - height[j];
31                j--;
32            }
33            else
34            {
35                if(height[i]<secondHeight)
36                area += secondHeight - height[i];
37                i++;
38            }
39         }
40         return area;
41     }
42 };

 

posted @ 2015-09-08 16:58  醉剑客  阅读(134)  评论(0编辑  收藏  举报