ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode42:接雨水(Trapping Rain Water)

2019-09-15 15:44:23  阅读:316  来源: 互联网

标签:map elevation Marcos int water 雨水 Water Rain LeetCode42


英文题目:

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. Thanks Marcos for contributing this image!

Example:

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

中文题目:

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
在这里插入图片描述

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢 Marcos 贡献此图。

示例:

输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6

解答:

C++
class Solution {
public:
    int trap(vector<int>& height) {
        int res=0;
        stack<int> stk;
        
        for (int i=0;i<height.size();i ++)
        {
            int last=0;
            while (stk.size() && height[stk.top()] <=height[i])
            {
                int t=stk.top();
                stk.pop();
                res +=(i-t-1)*(height[t]-last);
                last=height[t];
            }
            if (stk.size()) res +=(i-stk.top()-1)*(height[i]-last);
            stk.push(i);
        }
        return res;
    }
};

标签:map,elevation,Marcos,int,water,雨水,Water,Rain,LeetCode42
来源: https://blog.csdn.net/XB_please/article/details/100855023

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有