2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_42.java 1.56 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2021-02-02 14:16 . bytedance
package com.hit.basmath.interview.top_interview_questions.hard_collection.others;
/**
* 42. 接雨水
* <p>
* 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
* <p>
* 示例 1:
* <p>
* 输入: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 个单位的雨水(蓝色部分表示雨水)。
* <p>
* 示例 2:
* <p>
* 输入:height = [4,2,0,3,2,5]
* 输出:9
* <p>
* 提示:
* <p>
* n == height.length
* 0 <= n <= 3 * 10^4
* 0 <= height[i] <= 10^5
*/
public class _42 {
public int trap(int[] height) {
if (height.length < 3) return 0;
int ans = 0;
int l = 0, r = height.length - 1;
// find the left and right edge which can hold water
while (l < r && height[l] <= height[l + 1]) l++;
while (l < r && height[r] <= height[r - 1]) r--;
while (l < r) {
int left = height[l];
int right = height[r];
if (left <= right) {
// add volum until an edge larger than the left edge
while (l < r && left >= height[++l]) {
ans += left - height[l];
}
} else {
// add volum until an edge larger than the right volum
while (l < r && height[--r] <= right) {
ans += right - height[r];
}
}
}
return ans;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助