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;
    }
};
相关推荐
海石2 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石2 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx2 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie3 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃4 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录5 小时前
prompt-optimizer skill
算法
万法若空5 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时5 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的6 小时前
汇编——内存
开发语言·汇编·算法·网络安全
tachibana26 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode