zoukankan      html  css  js  c++  java
  • Leetcode 42.接雨水

    题目描述:

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

    示例:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/trapping-rain-water

    思路:在每一点处雨水的高度 = min(该点左边高度的最大值,该点右边高度的最大值)-当前高度

    方法一:遍历数组,找到每一点的左右最大高度值

    /**
     * @param {number[]} height
     * @return {number}
     */
    var trap = function(height) {
        if(height == null || height.length == 0){
            return 0;
        }
        let n = height.length;
        let left_max = new Array(n);
        let right_max = new Array(n);
        left_max[0] = height[0];
        right_max[n-1] = height[n-1];
        let res = 0;
        for(let i = 1; i < n; i++){
            left_max[i] = Math.max(left_max[i-1], height[i]);
        }
        for(let j = n-2; j >= 0; j--){
            right_max[j] = Math.max(right_max[j+1],height[j]);
            res += Math.min(right_max[j], left_max[j]) - height[j];
        }
        return res;
    };
    

      

  • 相关阅读:
    WPF元素之间的关系
    依赖属性
    多线程显示运行状态
    WPF 基本知识
    SQL 这个删除重复行怎么做
    路由事件
    WPF的数据邦定
    SQL对表中XML列的查询
    WMI访问注册表读取系统信息
    创建第一个WPF应用程序
  • 原文地址:https://www.cnblogs.com/ZLDJ-15-516/p/11027059.html
Copyright © 2011-2022 走看看