前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode42. 接雨水

LeetCode42. 接雨水

作者头像
mathor
发布2018-08-17 15:38:28
1.3K0
发布2018-08-17 15:38:28
举报
文章被收录于专栏:mathor
题目链接:LeetCode42

 有人说用贪心,我觉得这是一个单调栈的板子题,构建一个单调递减栈(栈底到栈顶是递减的),要想能够收集雨水,栈中至少要两个数字,才能形成一个坑,先pop一个数字,这个数字就是最低值,再peek一个数字,peek的数字和遍历的到的值进行比较,较小的值减去最低值的高度,得出的这个高度就是能蓄水的高度,底就是做右边界的值相减

代码语言:javascript
复制
class Solution {
    public int trap(int[] height) {
        if(height == null || height.length == 0) 
            return 0;
        int sumArea = 0;
        Stack<Integer> stack = new Stack<Integer>();
        for(int right = 0;right < height.length;right++) {
            while(!stack.isEmpty() && height[stack.peek()] < height[right]) { 
                if(stack.size() >= 2) {
                    int j = stack.pop();
                    int left = stack.peek();
                    int curArea = (Math.min(height[right],height[left]) - height[j]) * (right - left - 1);
                    sumArea += curArea;
                }
                else
                    stack.pop();
            }
            stack.push(right);
        }
        return sumArea;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-08-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接:LeetCode42
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档