Leetcode 42.接雨水 JavaScript (Day 3)

js一刷(法一)

javascript 复制代码
var trap = function (height) {
   let ans=0;
   const n=height.length;
   let i=0;
   let j=n-1;
   let left_max=0,right_max=0;
   while(i<j){
    left_max=Math.max(left_max,height[i]);
    right_max=Math.max(right_max,height[j]);
    if(left_max<right_max){
        ans+=left_max-height[i];
        i++;
    }
    else {
        ans+=right_max-height[j];
        j--;
    }

}
 return ans;

};

js一刷(法二)

javascript 复制代码
var trap = function (height) {
    let ans = 0;
    let leftMax = [], rightMax = [];
    leftMax[0] = height[0];
    rightMax[height.length - 1] = height[height.length - 1];
    for (let i = 1; i < height.length; i++)
        leftMax[i] = Math.max(height[i], leftMax[i - 1]);
    for (let i = height.length - 2; i >= 0; i--)
        rightMax[i] = Math.max(height[i], rightMax[i + 1]);

    for (let i = 1; i < height.length - 1; i++) {
        let left_max = leftMax[i], right_max = rightMax[i];
        let s = Math.min(left_max, right_max) - height[i];
        ans += s;

    }
    return ans;

};

核心思想:一开始我想着一大块面积一大块的算,但实现不了。思路来自灵神
将每一索引处看成一个桶,我们要知道他的左边最大高度和 右边最大高度 算出通的面积再次减去索引处本来的高度

javascript 复制代码
let s = Math.min(left_max, right_max) - height[i];

有两种方法,一种是在遍历前,先用两个数组分别记录每个索引处的左边最大值和右边最大值(法二)这种方法空间复杂度高

第二种是双指针,边算最大高度边做累加,对于左边,我们可以明确知道左边的最大高度,但这时候不知道右边,怎么办呢,如果此时left_max<right_max,就可以用于计算了,右边同理
这种方法需要注意循环终止的条件是i<j,而不是i!=j,因为i和j可能会刚好错过,导致无限循环

算法核心

javascript 复制代码
left_max=Math.max(left_max,height[i]);
right_max=Math.max(right_max,height[j]);

leftMax[i] = Math.max(height[i], leftMax[i - 1]);
rightMax[i] = Math.max(height[i], rightMax[i + 1]);

长得有点像递归

相关推荐
深邃-1 小时前
【数据结构与算法】-二叉树(2):实现顺序结构二叉树(堆的实现),向上调整算法,向下调整算法,堆排序,TOP-K问题
数据结构·算法·二叉树·排序算法·堆排序··top-k
We་ct4 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程8 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮9 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说9 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove10 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
leoufung10 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了10 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL10 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰11 小时前
C++ 排列组合完整指南
开发语言·c++·算法