So I have an assignment where I have to recreate a 3d chessboard that is a RxC grid of squares each being a different height. If the chessboard is water tight, and someone pours water all over it until it can hold no more water, it will hold a fixed amount of water. If the board is already holding its maximum volume of water, any excess water poured onto the board will drain off the edges, there is no tall …
我在一份试卷中解决了这个问题,并在答案书中找到了一个解决方案。我无法理解其背后的算法。谁能解释一下这个算法是如何工作的?
给定 n 个非负整数表示海拔图,其中每个条形的宽度为 1,计算下雨后它能够捕获多少水。
例如,给定输入
[0,1,0,2,1,0,1,3,2,1,2,1]
Run Code Online (Sandbox Code Playgroud)
返回值将是
6
Run Code Online (Sandbox Code Playgroud)
根据答案书的解决方案是这样的
public class Solution {
public int trap(int[] height) {
if (height.length <=2 )
return 0;
int h = 0, sum = 0, i = 0, j = height.length - 1;
while(i < j)
{
if ( height[i] < height[j] )
{
h = Math.max(h,height[i]);
sum += h - height[i];
i++;
}
else
{
h = Math.max(h,height[j]);
sum += h - height[j];
j--;
}
}
return sum;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢