首页 > 移动平台 > 详细

42. Trapping Rain Water

时间:2019-07-13 10:34:57      阅读:76      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/forPrometheus-jun/p/11179595.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!