LeetCode 42 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!app

根據輸入的數組組成的直方圖計算能夠「盛水」的面積。idea是從第一個非零數開始標記爲lastMarkedheight,這個lastMarkedheight做爲一個能夠盛水的高度基準,爲了肯定它是安全的,須要遍歷它以後的數,要是有更高的數字則是安全的,不然把lastMarkedheight的值下降爲可搜索到的最高高度。在確認安全以後繼續遍歷數組,遇到矮的則把高度差做爲儲水量加起來,遇到比lastMarkedheight高的就從新判斷那個值是否安全並更新lastMarkedheight。ide

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         vector<int>::iterator it;
 5         int sumWater=0;
 6         int lastMarkedHight=0;
 7         for(it = height.begin();it!=height.end();it++){
 8             if(lastMarkedHight==0 && *it == 0)//前面的0無視掉
 9               continue;
10             if(lastMarkedHight==0 && *it != 0){//第一個非零做爲lastMarkedHight
11               lastMarkedHight = *it;
12             }
13             if(lastMarkedHight!=0 && *it>=lastMarkedHight){//判斷是否安全
14                 int a = 0;
15                 bool findLarger = false;
16                 for(vector<int>::iterator tempIt=it+1;tempIt!=height.end();tempIt++){//找是否有更高的
17                     if(*tempIt>*it){
18                         findLarger = true;
19                         break;
20                     }
21                 }
22                 if(findLarger){//安全
23                     lastMarkedHight = *it;
24                     continue;
25                 }
26                 else{//找it後最高的一個數做爲lastMarkedHight
27                     while(find(it+1,height.end(),*it-a)==height.end() && *it-a>0){
28                         a++;
29                     }
30                 lastMarkedHight = *it-a;
31                 }
32             continue;
33             }
34             if(lastMarkedHight!=0 && *it<lastMarkedHight && it!=height.end()-1){
35                 sumWater = sumWater+(lastMarkedHight-*it);//遇到矮的加儲水量
36                 cout<<sumWater<<endl;
37                 continue;
38             }
39         }
40         return sumWater;
41     }
42 };
相關文章
相關標籤/搜索