leetcode42. 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 Marcosfor contributing this image!

题目如上,求给定的数组所能容纳的“雨水数量“。

首先从图可以看出,能容纳雨水的部分都有一个特点,那就是两边高中间低,只有这样才可以盛下”雨水“,因此只要在整个数组当中,找出符合此条件的部分,就完成了第一步。

而具体的实现就是在当前位置之后,找出比当前元素大或相等的下一个元素,这两个元素就可以构成两条边,而这两条边构成的容器所能容纳的”雨水数量“=min(left,right)*(left-right-1)-(left~right中间部分的元素之和)

在整个数组范围内找出这样的部分,并求每个部分所能容纳的”雨水数量“,最后将得到的”雨水数量“相加即可。

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         int sum=0,flag;
 5         for(int i=0;i<height.size();++i){
 6             for (int j=i+1;j<height.size();++j) {
 7                 if(height[j]>=height[i]){
 8                     sum+=height[i]*(j-i-1);
 9                     for(int m=i+1;m<j;++m){
10                         sum-=height[m];
11                     }
12                     i=j-1;
13                     break;
14                 }
15                 if(j==height.size()-1){
16                     vector<int>::iterator maxelem = max_element(height.begin()+i+1, height.end());
17                     flag = std::distance(height.begin(), maxelem);
18                     sum+=height[flag]*(flag-i-1);
19                     for(int m=i+1;m<flag;++m){
20                         sum-=height[m];
21                     }
22                     i=flag-1;
23                 }
24             }
25         }
26         return sum;
27     }
28 };
 
原文地址:https://www.cnblogs.com/yeqingqian/p/7631824.html