zoukankan      html  css  js  c++  java
  • leetcode 42 Trapping Rain Water(Hard)

    题目来源:leetcode 42 Trapping Rain Water

    题目描述:

    给定 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

    解题思路:

    可以拿总的(总长最高柱子的高度)-白色的(两个循环求得)-黑色的(每个柱子的高度1),就是雨水的量,具体见代码:

    class Solution {
    public:
        int trap(vector<int>& height) {
            int white=0,max=0,black=0,total=0;
            int size=height.size();
            int i;
            for(i=0;i<size;i++)
            {
                if(height[i]>max){
                    white+=(height[i]-max)*i;
                    max=height[i];
                }
            }
            max=0;
            for(i=size-1;i>=0;i--)
            {
                if(height[i]>max){
                    white+=(height[i]-max)*(size-i-1);
                    max=height[i];
                }
            }
            for(i=0;i<size;i++)
                black+=height[i];
            total=size*max;
            return total-black-white;
        }
    };
    
  • 相关阅读:
    通用sqlserver分页存储过程
    JSONP解决跨域请求
    laravle框架
    XML作用
    mysql 中的常用查询
    smarty模板技术
    Cookie和Session 会话技术
    正则表达式
    Mongodb常用知识点
    PHP之PDO
  • 原文地址:https://www.cnblogs.com/yjcoding/p/13224364.html
Copyright © 2011-2022 走看看