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

长得有点像递归

相关推荐
文丑颜不良啊19 分钟前
LeetCode1861~1880题目解析
java·leetcode
文丑颜不良啊38 分钟前
LeetCode1921~1940题目解析
java·leetcode
一只不想敲代码的程序猿1 小时前
如何更高效地拆解问题?
算法
微尘hjx2 小时前
【Deep-OC-SORT 02】多轨迹算法Deep-OC-SORT-相对 OC-SORT 的改进点
人工智能·算法·yolo·目标跟踪·视觉检测·ultralytics·deep-oc-sort
梦帮科技2 小时前
意识启发式量子隧穿退火算法用于全局优化 (CITA) 完整技术指南
网络·人工智能·算法·量子计算·模拟退火算法
一去不复返的通信er3 小时前
排序 + 双指针:力扣15三数之和
算法·leetcode
文丑颜不良啊3 小时前
LeetCode1901~1920题目解析
java·leetcode
toooooop83 小时前
CRMEB 故障排查笔记:安全网关只放行 GET/POST 怎么办
前端·javascript·vue.js·thinkphp6·crmeb
软件技术NINI4 小时前
基于SpringBoot和Vue的项目评审系统
javascript·vue.js·spring boot·后端·spring·毕业设计·毕设
Pniubi4 小时前
力扣3无重复字符的最长字串(滑动窗口)
算法·leetcode·职场和发展