版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kangyucheng/article/details/82987339
题目:链接
给定 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
解题思路:
第一步:遍历整个数组,找到整个数组中最高的柱子,做好记录
第二步:从左向右遍历到那个最高柱子,找到并对左边的最大值做好记录,一旦有柱子比这个最大值低,那么这个位置可以装水
第三步:从右向左遍历到那个最高柱子,找到并对右边的最大值做好记录,一旦有柱子比这个最大值低,那么这个位置可以装水
代码:
class Solution {
public int trap(int[] height) {
int max = 0;
int maxIndex = 0;
for(int i =0 ;i< height.length; i++){
if (max < height[i]){
max = height[i];
maxIndex = i;
}
}
int sum = 0;
int maxLeft = 0;
int maxRight = 0;
for (int a=0 ; a<maxIndex; a++){
if (height[a]>=maxLeft){
maxLeft = height[a];
}
else{
sum+= maxLeft-height[a];
}
}
for (int b=height.length-1 ; b>maxIndex; b--){
if (height[b]>=maxRight){
maxRight = height[b];
}
else{
sum+= maxRight-height[b];
}
}
System.out.print(sum);
return sum;
}
}
手动测试
public class Solution {
public int trap(int[] height) {
int max = 0;
int maxIndex = 0;
for(int i =0 ;i< height.length; i++){
if (max < height[i]){
max = height[i];
maxIndex = i;
}
}
int sum = 0;
int maxLeft = 0;
int maxRight = 0;
for (int a=0 ; a<maxIndex; a++){
if (height[a]>=maxLeft){
maxLeft = height[a];
}
else{
sum+= maxLeft-height[a];
}
}
for (int b=height.length-1 ; b>maxIndex; b--){
if (height[b]>=maxRight){
maxRight = height[b];
}
else{
sum+= maxRight-height[b];
}
}
System.out.print(sum);//6
return sum;
}
public static void main(String[] args){
int[] height={0,1,0,2,1,0,1,3,2,1,2,1};
Solution solution = new Solution();
solution.trap(height);
}
}