美文网首页
LeetCode 第42题:接雨水

LeetCode 第42题:接雨水

作者: 放开那个BUG | 来源:发表于2020-06-20 14:29 被阅读0次

1、前言

题目描述

2、思路

此题与《盛最多水的容器》的区别在于,《盛最多水的容器》可以直接根据两边的索引求值,然后分别进行递归。这道题不能直接求值(能不能递归不知道哈),只能针对每一个列能装多少水进行计算,所以最重要的是计算出每个列能装多少水。

对于为止 i 能装的水的格数:

water[i] = min(
               # 左边最高的柱子
               max(height[0..i]),  
               # 右边最高的柱子
               max(height[i..end]) 
            ) - height[i]

3、代码

1⃣️ 暴力解法:

public int trap(int[] height) {
        int res = 0, n = height.length;
        for(int i = 1; i < n - 1; i++){
            int lmax = 0, rmax = 0;

            for(int j = i; j >= 0; j--){
                if(height[j] > lmax){
                    lmax = height[j];
                }
            }

            for(int j = i; j < n; j++){
                if(height[j] > rmax){
                    rmax = height[j];
                }
            }

            res += Math.min(lmax, rmax) - height[i];
        }

        return res;
    }

2⃣️ 使用备忘录

class Solution {
    public long maxWater (int[] arr) {
        if(arr == null || arr.length == 0){
            return 0;
        }

        int n = arr.length;
        int[] leftMemo = new int[n];
        int lMax = arr[0];
        for(int i = 0; i < n; i++){
            lMax = Math.max(lMax, arr[i]);
            leftMemo[i] = lMax;
        }

        int[] rightMemo = new int[n];
        int rMax = arr[n - 1];
        for(int i = n - 1; i >= 0; i--){
            rMax = Math.max(rMax, arr[i]);
            rightMemo[i] = rMax;
        }

        int res = 0;
        for(int i = 0; i < n; i++){
            res += Math.min(leftMemo[i], rightMemo[i]) - arr[i];
        }

        return res;
    }
}

相关文章

  • LeetCode 第42题:接雨水

    1、前言 2、思路 对于为止 i 能装的水的格数: 3、代码 1⃣️ 暴力解法: 2⃣️ 使用备忘录 3⃣️ 双指针

  • 42. 接雨水

    42. 接雨水[https://leetcode.cn/problems/trapping-rain-water/...

  • 题库笔记

    42. 接雨水[https://leetcode-cn.com/problems/trapping-rain-wa...

  • Leetcode 42题 接雨水(Trapping Rain W

    题目链接 https://leetcode-cn.com/problems/trapping-rain-water...

  • LeetCode42 接雨水

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

  • [LeetCode]42. 接雨水

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

  • LeetCode#42接雨水

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

  • Leetcode42: 接雨水

    【题目描述】 【思路】思路1: 找左边最大值与右边最大值,取较小值为可达高度。再减去这个位置本来的高度,为积水高度...

  • LeetCode-42-接雨水

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

  • LeetCode - 42. 接雨水

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

网友评论

      本文标题:LeetCode 第42题:接雨水

      本文链接:https://www.haomeiwen.com/subject/akxbxktx.html