【算法】【线性表】【数组】Trapping Rain Water(接水量)

1  题目

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) 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.
Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

  • n == height.length
  • 1 <= n <= 2 * 104
  • 0 <= height[i] <= 105

2  解答

2.1  比较好理解的

总的接水量 = 每个元素的接水量的和,而每个元素的接水量 = min(leftMax, rightMax) - 自己

复制代码
class Solution {
    public int trap(int[] height) {
        // 记录总的接水量
        int res = 0;
        // 总的接水量 = 每个元素的接水量的和
        // 每个元素的接水量 = min(leftMax, rightMax) - 自己
        // 求每个元素的左侧最大值
        int len = height.length;
        int[] leftMax = new int[len];
        leftMax[0] = height[0];
        for (int i=1; i<len; i++) {
            leftMax[i] = Math.max(leftMax[i-1], height[i]);
        }
        // 求每个元素的右侧最大值
        int[] rightMax = new int[len];
        rightMax[len-1] = height[len-1];
        for (int i=len-2; i>=0; i--) {
            rightMax[i] = Math.max(rightMax[i+1], height[i]);
        }
        // 计算每个元素的接水量
        for (int i=0; i<len; i++) {
            res += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return res;
    }
}
复制代码

 

posted @   酷酷-  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-12-26 【问题记录】【SpringBoot】【Swagger】启动的时候,有一堆Swagger冲突的日志,看着不爽 Generating unique operation named
2022-12-26 【问题记录】【SpringBoot】启动不加载某个Starter,通过代码控制某个Starter加载
2022-12-26 【问题记录】【SpringBoot】Filter中抛出的异常不会走RestControllerAdvice全局异常捕获
点击右上角即可分享
微信分享提示