# 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.

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.

Example:

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

### 解法1

``````class Solution {
public:
int trap(vector<int>& height) {
int l=0,r=height.size()-1,level=0,water=0;
while(l < r){
int lower = height[height[l]<height[r]?l++:r--];
level = max(lower,level);
water += level-lower;
}
return water;
}
};
``````

### 解法2

``````class Solution {
public:
int trap(vector<int>& height) {
stack<int> st;
int i = 0,n = height.size(),res = 0;
while(i < n){
if (st.empty() || height[i]<=height[st.top()]){
st.push(i++);
}else{
int t = st.top();
st.pop();
if (st.empty()) continue;
res += (min(height[i],height[st.top()])-height[t]) * (i-st.top()-1);
}
}
return res;
}
};
``````

https://blog.csdn.net/viewsky11/article/details/80571413

https://leetcode.com/problems/trapping-rain-water/discuss/17364/7-lines-C-C++

http://www.cnblogs.com/grandyang/p/4402392.html