前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 42 Trapping Rain Water

Leetcode 42 Trapping Rain Water

作者头像
triplebee
发布2018-01-12 15:06:19
4440
发布2018-01-12 15:06:19
举报

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.

For example,  Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

image.png
image.png

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!

左右两点,小的向中间缩,同时小的一侧与那一侧最大值的高度差,得出的为这个点的水深。

代码语言:javascript
复制
class Solution {
public:
    int trap(vector<int>& height) {
        int l=0,r=height.size()-1,result=0,ml=0,mr=0;
        while(l<r)
        {
            if(height[l]<height[r])
            {
                if(height[l]<ml)
                    result+=ml-height[l];
                else
                    ml=height[l];
                l++;
            }
            else
            {
                if(height[r]<mr)
                    result+=mr-height[r];
                else
                    mr=height[r];
                r--;
            }
        }
        return result;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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