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

通过次数773.8K提交次数1.2M通过率63.1%

接雨水问题的解决方案,同样采用双指针法

java 复制代码
public int trap(int[] height) {
    int left = 0;
    int right = height.length - 1;
    int leftMax = 0;
    int rightMax = 0;
    int result = 0;

    while (left < right) {
        if (height[left] < height[right]) {
            if (height[left] >= leftMax) {
                leftMax = height[left];
            } else {
                result += leftMax - height[left];
            }
            left++;
        } else {
            if (height[right] >= rightMax) {
                rightMax = height[right];
            } else {
                result += rightMax - height[right];
            }
            right--;
        }
    }

    return result;
}
相关推荐
玉树临风ives2 分钟前
atcoder ABC 457 题解
数据结构·c++·算法
DFT计算杂谈4 分钟前
AMSET 设置多核并行计算
java·前端·css·html·css3
驭渊的小故事11 分钟前
Java数据结构集合框架(栈(Stack)的详细解析)2000字详细解析
数据结构
Gerardisite21 分钟前
CRM、ERP、OA 如何连接企业微信?QiWe 提供标准化解决方案
java·python·机器人·自动化·企业微信
城管不管22 分钟前
Maven Helper
java·macos·intellij-idea
ch.ju25 分钟前
Java程序设计(第3版)第三章——数组的动态获取
java·开发语言
禧西28 分钟前
面试准备——agent和大模型_1
面试·职场和发展
Java知识技术分享35 分钟前
策略模式的两种实现:抽象类和接口
java·spring·策略模式
液态不合群39 分钟前
Redis--哨兵机制与CAP定理
java·redis·bootstrap
曹牧41 分钟前
Java:PDF文件扁平化处理
java·开发语言·pdf