来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
1.题目
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [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
class Solution {
public int trap(int[] height) {
}
}
2.JAVA解答
首先找到,最高点,求出整个矩形面积,最高点前从0开始递推,减去空面积和柱子面积;最高点后从数组最大索引往前递推,减去空面积和柱子面积,时间复杂度O(N),空间复杂度O(1)。
class Solution {
public int trap(int[] height) {
int res =0;
int maxIndex =0;
int maxHeight=0;
for(int i=0;i<height.length;i++){
if(height[i]>maxHeight){
maxIndex=i;
maxHeight=height[i];
}
}
res = maxHeight*height.length;
res -= maxHeight;
int tempHeight=0;
for(int i=0;i<maxIndex;i++){
if(height[i]>=tempHeight){
tempHeight=height[i];
}
res -= (maxHeight-tempHeight);
res -= height[i];
}
tempHeight=0;
for(int j=(height.length-1);j>maxIndex;j--){
if(height[j]>=tempHeight){
tempHeight=height[j];
}
res -= (maxHeight-tempHeight);
res -= height[j];
}
return res;
}
}
网友评论