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!

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         if(height.size() < 3) return 0;
 5         int res = 0;
 6         int left = 0;
 7         int right = height.size() - 1;
 8         int leftMax = height[0];
 9         int rightMax = height[right];
10 
11         while(left != right){
12             if(leftMax < rightMax){
13                 left++;
14                 if(height[left]<leftMax){
15                     res +=leftMax - height[left];
16                 }else{
17                     leftMax = height[left];
18                 }
19             }else{
20                 right--;
21                 if(height[right] < rightMax){
22                     res += rightMax- height[right];
23                 }else{
24                     rightMax = height[right];
25                 }
26             }
27         }
28         return res;
29     }
30 };

 

原文地址:https://www.cnblogs.com/wxquare/p/5065092.html