当前位置:网站首页>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;
}
边栏推荐
- 案例 | 重庆银行流动数据安全挑战及应对实践
- 《nlp入门+实战:第八章:使用Pytorch实现手写数字识别》
- PHP高级开发案例(1):使用MYSQL语句跨表查询无法导出全部记录的解决方案
- View mysql deadlock syntax
- typescript type 和 interface 的区别
- 移动端响应式适配的方法
- [Ryerson emotional speaking/singing audiovisual dataset (RAVDESS)]
- 移动支付线上线下支付场景
- docker+网桥+redis主从+哨兵模式
- db2中kettle报错 Field [XXX] is required and couldn‘t be found 解决方法
猜你喜欢
How to systematically plan and learn software testing?
深度学习——以CNN服装图像分类为例,探讨怎样评价神经网络模型
DIY电工维修如何拆卸和安装开关面板插座
Detailed analysis of scaffolding content
6口全千兆二层网管型工业以太网交换机千兆2光4电光纤自愈ERPS环网交换机
SQL query String field less than 10 how to check
从图文展示到以云为核,第五代验证码独有的策略情报能力
sql注入一般流程(附例题)
什么是数字孪生智慧城市应用场景
This Thursday evening at 19:00, the fourth live broadcast of knowledge empowerment丨The realization of equipment control of OpenHarmony smart home project
随机推荐
Polygon zkEVM network node
There are too many systems, how to realize multi-account interworking?
元宇宙“吹鼓手”Unity:疯狂扩局,悬念犹存
Gigabit 2 X light 8 electricity management industrial Ethernet switches WEB management - a key Ring Ring net switch
kingbaseES V8R2/R3 表在指定表空间,为何显示为默认表空间?
SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
The general SQL injection flow (sample attached)
Detailed analysis of scaffolding content
RSS订阅微信公众号初探-feed43
Introduction to the memory model of the JVM
出现504怎么办?由于服务器更新导致的博客报504错误[详细记录]
复现20字符短域名绕过
使用serve搭建本地服务器
new Date将字符串转化成日期格式 兼容IE,ie8如何通过new Date将字符串转化成日期格式,js中如何进行字符串替换, replace() 方法详解
JVM的内存模型简介
MySQL查询优化与调优
函数,递归以及dom简单操作
LeetCode每日一题(2285. Maximum Total Importance of Roads)
怎样提高网络数据安全性
4路双向HDMI综合业务高清视频光端机8路HDMI高清视频光端机