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!

根据输入的数组组成的直方图计算可以“盛水”的面积。idea是从第一个非零数开始标记为lastMarkedheight,这个lastMarkedheight作为一个可以盛水的高度基准,为了确定它是安全的,需要遍历它之后的数,要是有更高的数字则是安全的,否则把lastMarkedheight的值降低为可搜索到的最高高度。在确认安全之后继续遍历数组,遇到矮的则把高度差作为储水量加起来,遇到比lastMarkedheight高的就重新判断那个值是否安全并更新lastMarkedheight。

 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 };

 

posted @ 2016-03-24 07:01  熊阳  阅读(590)  评论(0编辑  收藏  举报