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