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 };
相關文章
相關標籤/搜索