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]);

长得有点像递归

相关推荐
ValhallaCoder14 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮14 小时前
AI 视觉连载1:像素
算法
智驱力人工智能14 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
Moment15 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
爱敲代码的小鱼15 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
孞㐑¥15 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风15 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風15 小时前
8.1 PFH&&FPFH
图像处理·算法
NEXT0616 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
代码游侠16 小时前
学习笔记——设备树基础
linux·运维·开发语言·单片机·算法