42. Trapping Rain Water

description:

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.
Note:
https://leetcode.com/problems/trapping-rain-water/.
Example:

Example:

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

answer:

class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> st;
        int n = height.size();
        int i = 0, 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[st.top()], height[i]) - height[t]) * (i - st.top() - 1);
            }
        }
        return res;
    }
};

relative point get√:

hint :

  • 第一种用堆栈去做的思路大致如下:堆栈里存入的是坐标,如果现在加入的这个数和前面那个数比小,那就一直加入,如果大,那就证明最起码能和它前面那个数形成一个水坑,但是考虑到不能重复计算水面积,所以只是覆盖他们这一层,就是这个水坑的计算是横着一层一层的填满的,自己拿草纸走一遍例子就行了....瞬间明白了...
  • 第二种方法

42. Trapping Rain Water

上一篇:jvm 监控


下一篇:Android Studio出现Failed to open zip file问题的解决方法