当前位置:网站首页>42. 接雨水
42. 接雨水
2022-08-04 03:39:00 【小卢要刷力扣题】
前言
给定 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 个单位的雨水(蓝色部分表示雨水)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路

0位置最左20位置最右是不可能留下水的
19位置的最大高度假设6,要结算算水量
需要求6的左边,右边部分的max,以13做瓶颈,
因为6它的左边这么多最大值还没看过,但它的最大值是17,恐怕它真实的左边最大值是大于17的。
而我右边的最大值,这可是个真实最大值,所以6位置的水量就是13-6= 7格子水
左边跟右边max谁小就先结算那边的水量
代码
public static int trap(int[] arr) {
if (arr == null || arr.length < 2) {
return 0;
}
int N = arr.length;
int L = 1;
int leftMax = arr[0];
int R = N - 2;
int rightMax = arr[N - 1];
int water = 0;
while (L <= R) {
if (leftMax <= rightMax) {
water += Math.max(0, leftMax - arr[L]);
leftMax = Math.max(leftMax, arr[L++]);
} else {
water += Math.max(0, rightMax - arr[R]);
rightMax = Math.max(rightMax, arr[R--]);
}
}
return water;
}
边栏推荐
- 6口全千兆二层网管型工业以太网交换机千兆2光4电光纤自愈ERPS环网交换机
- Basic form validation process
- How to systematically plan and learn software testing?
- XSS相关知识点
- 创新互融|华秋赋能助力OpenHarmony生态硬件开发落地
- 马尔可夫链
- 张量篇-应用案例
- Polygon zkEVM network node
- Mockito unit testing
- Postgresql source code (66) insert on conflict grammar introduction and kernel execution process analysis
猜你喜欢

逻辑漏洞----其他类型
SQL injection in #, - +, - % 20, % 23 is what mean?

复制带随机指针的链表

跨境电商看不到另一面:商家刷单、平台封号、黑灰产牟利

base address: environment variable

Significant differences between Oracle and Postgresql in PLSQL transaction rollback

复现20字符短域名绕过

劝退背后。

6口全千兆二层网管型工业以太网交换机千兆2光4电光纤自愈ERPS环网交换机

There are too many systems, how to realize multi-account interworking?
随机推荐
unsafe.Pointer, pointer, reference in golang
SQL query String field less than 10 how to check
A Preliminary Study of RSS Subscription to WeChat Official Account-feed43
FPGA parsing B code----serial 3
MySQL查询优化与调优
基本表单验证流程
网络工程师入门必懂华为认证体系,附系统学习路线分享
Implementing a server-side message active push solution based on SSE
仿牛客论坛项目梳理
十一种概率分布
Power button (LeetCode) 215. The first K largest elements in the array (2022.08.03)
基于Qt的目录统计QDirStat
JVM内存和垃圾回收-07.堆
2022 Hangzhou Electric Power Multi-School League Game 5 Solution
【翻译】Terraform和Kubernetes的交集
STM8S project creation (STVD creation) --- use COSMIC to create a C language project
SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
Mockito unit testing
Detailed analysis of scaffolding content
案例 | 重庆银行流动数据安全挑战及应对实践