Trapping Rain Water

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

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

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

 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 };
相关文章
相关标签/搜索