Trapping Rain Water(单调栈)

42. Trapping Rain Water
Hard

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.


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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

解题思路: 维护一个单调递减的栈 栈储存的是下标

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         int sta[100005],top=0,res=0;
 5         for(int i=0;i<height.size();i++){
 6             while(height[sta[top]]<height[i]&&top){   //维护一个单调递减的栈
 7                 int h=height[sta[top]];
 8                 top--;
 9                 if(top==0) break;
10                 res+=(min(height[sta[top]],height[i])-h)*(i-sta[top]-1);
11             } 
12             sta[++top]=i;
13         }
14         return res;
15     }
16 };
View Code

 

 1 class Solution {
 2 public:
 3     int trap(vector<int>& height) {
 4         int n=height.size();
 5         if(n==0) return 0;
 6         int left=0,right=n-1;
 7         int left_max=height[0];   //左边最高的
 8         int right_max=height[right];  //右边最高的
 9         int res=0;
10         while(left<=right){
11             if(left_max<right_max){  //找最短板
12                 res+=left_max-height[left++];
13                 left_max=max(left_max,height[left]);
14             }
15             else{
16                 res+=right_max-height[right--];
17                 if(right>=0)   //防止出现负数 RT
18                     right_max=max(right_max,height[right]);
19             }
20         }
21         return res;
22     }
23 };
24 
25 代码一
View Code

 

posted @ 2019-08-13 18:37  厂长在线养猪  Views(215)  Comments(0Edit  收藏  举报