• leetcode 42. 接雨水 JAVA


    题目:

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

    解题思路:

    class Solution {
        public int trap(int[] height) {
            // 至少三块方可积水
            if (height.length < 3) return 0;
    
            int i, result = 0, length = height.length;
    
            int[] L = new int[length];
            int[] R = new int[length];
    
            // 记录每个挡板的左/右边的最高挡板高度 L[0]和R[length-1]为0
            for (i = 1; i < length; i++) {
                L[i] = Math.max(L[i-1], height[i-1]);
                R[length - 1 - i] = Math.max(R[length-i], height[length-i]);
            }
    
            // 计算积水
            for (i = 0; i < length; i++) {
                if (L[i] > height[i] && R[i] > height[i]) {
                    result += Math.min(L[i], R[i]) - height[i]; //左右挡板的较小值减去其高度即可
                }
            }
            return result;
        }
    }
  • 相关阅读:
    字符串的输入输出 附带一道练习题
    NOIP2009 1.多项式输出
    算法--欧几里得
    小程序:2048
    虚函数和多态
    c++学习记录(十五)
    面向对象程序设计寒假作业3
    c++学习记录(十四)
    c++学习记录(十三)
    c++学习记录(十二)
  • 原文地址:https://www.cnblogs.com/yanhowever/p/10492609.html
Copyright © 2020-2023  润新知