day104—对向双指针—接雨水(LeetCode-42)

题目描述

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

示例 1:

复制代码
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 

示例 2:

复制代码
输入:height = [4,2,0,3,2,5]
输出:9

提示:

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

解决方案一:

1、用两个数组记录最大高度

2、结果计算公式:左右柱子最小值(短板)- 地面高度

函数源码:

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        int ans=0;
        int len = height.size();

        vector<int>left(len,height[0]);    //从左数最大
        for(int i=1;i<len;i++){
            left[i]=max(left[i-1],height[i]);
            
        }

        vector<int>right(len,height[len-1]);   //从右数最大
        for(int i=len-2;i>=0;i--){
            right[i]=max(right[i+1],height[i]);
            
        }

        for(int i=0;i<len;i++){
            ans+=min(left[i],right[i])-height[i];
            cout<<"l-"<<left[i]<<"r-"<<right[i]<<" "<<ans<<endl;
        
        }

        return ans;
    }
};

解决方案二:

1、用双指针代替两个数组

2、关注移动逻辑:高度恒高于前缀-->移动高度小的指针

函数源码:

cpp 复制代码
class Solution {
public:
    int trap(vector<int>& height) {
        int len=height.size();
        int ans=0;
        int x=0;
        int y=len-1;
        int left=height[x]; //最左边开始
        int right=height[y];//最右边开始
        
        while(x<y){ //双指针
            left=max(left,height[x]);
            right=max(right,height[y]);
            if(left<right){
                ans+=min(left,right)-height[x];
                x+=1;
            }
            else{
                ans+=min(left,right)-height[y];
                y-=1;
            }
        }

        return ans;
    }
};
相关推荐
Wang's Blog26 分钟前
PostgreSQL笔记49:向量检索核心算法、索引调优与过滤策略深度解析
笔记·算法·postgresql
疯狂打码的少年34 分钟前
【数据结构】交换类排序:冒泡与快速排序
数据结构·笔记·算法·排序算法
Nil2081 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
高频因子挖掘机1 小时前
QuantDash 成交量单位统一实战:从“手”到“股”的跨市场量化数据清洗全流程
后端·算法·github
hn小菜鸡1 小时前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
Escalating_xu1 小时前
【C++ STL简介】从六大组件到容器、迭代器与算法协作
java·c++·算法
纪念 2292 小时前
算法二叉树(一)
算法
liulilittle2 小时前
llmx 学习手册 06 —— CPU 指令集优化(AVX-512 三层演进)
c++·学习·算法·ai·llm
土司大王3 小时前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王3 小时前
LeetCode hot100——回文链表
算法·leetcode·链表