https://leetcode-cn.com/problems/trapping-rain-water/
难度困难2633收藏分享切换为英文接收动态反馈
给定 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
0 <= n <= 3 * 104
0 <= height[i] <= 105
通过次数307,551提交次数534,773
class Solution {
public int trap(int[] height) {
//双指针
if(height.length <= 2) return 0;
int max1 = 0;
int max2 = height.length-1;
int ans =0;
int x = 0;
int y = height.length-1;
int min = 0;
while(x<y)
{
if(height[x]>height[max1]) max1=x;
if(height[y]>height[max2]) max2=y;
min = Math.min(height[max1],height[max2]);
if(height[x]<=height[y])
{
x++;
if(height[x] < min)
{
ans+=min-height[x];
}
}
else
{
y--;
if(height[y] < min)
{
ans+=min-height[y];
}
}
}
return ans;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69168.html