1 Star 0 Fork 0

amusement1234/LeetCode_Java

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
42.接雨水.java 1.74 KB
Copy Edit Raw Blame History
amusement1234 authored 2021-11-14 21:13 +08:00 . 1
/*
* @lc app=leetcode.cn id=42 lang=java
*
* [42] 接雨水
*
* https://leetcode-cn.com/problems/trapping-rain-water/description/
*
* algorithms
* Hard (46.53%)
* Likes: 631
* Dislikes: 0
* Total Accepted: 32.7K
* Total Submissions: 70K
* Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
*
* 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
*
*
*
* 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。 感谢
* Marcos 贡献此图。
*
* 示例:
*
* 输入: [0,1,0,2,1,0,1,3,2,1,2,1]
* 输出: 6
*
*/
// @lc code=start
class Solution {
public int trap(int[] height) {
// // 解法1:暴力
// int res = 0;
// int n = height.length;
// for (int i = 1; i < n - 1; i++) {
// int max_left = 0, max_right = 0;
// for (int j = i; j < n; j++) {
// max_right = Math.max(max_right, height[j]);
// }
// for (int j = i; j >= 0; j--) {
// max_left = Math.max(max_left, height[j]);
// }
// res += Math.min(max_left, max_right) - height[i];
// }
// return res;
// 解法2:双指针
if (height.length == 0)
return 0;
int n = height.length;
int left = 0, right = n - 1;
int ans = 0;
int l_max = height[0];
int r_max = height[n - 1];
while (left <= right) {
l_max = Math.max(l_max, height[left]);
r_max = Math.max(r_max, height[right]);
if (l_max < r_max) {
ans += l_max - height[left];
left++;
} else {
ans += r_max - height[right];
right--;
}
}
return ans;
}
}
// @lc code=end
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/amusement1234/LeetCode_Java.git
git@gitee.com:amusement1234/LeetCode_Java.git
amusement1234
LeetCode_Java
LeetCode_Java
master

Search