我试图在这里解决这个问题:https://leetcode.com/problems/trapping-rain-water/#/description
我的代码提供的答案不正确,但我无法理解原因。当我看着它并且通过我的脑袋时,我无法弄清楚它有什么问题。
这是我的解决方案: (如果可能的话,请不要向我提供有关更有效的方法的信息,我想尝试自己解决这个问题。)
public class Solution {
public int trap(int[] height) {
int totalWaterTrapped = 0;
for (int i = 0; i < height.length; i++){
if (i == 0){
continue;
} else if (i == (height.length - 1)){
continue;
} else {
int tallestLeftwardHeight = height[i];
for (int x = i; x >= 0; x--){
if (height[x] > tallestLeftwardHeight){
tallestLeftwardHeight = x;
}
}
int tallestRightwardHeight = height[i];
for (int y = i; y < height.length; y++){
if (height[y] > tallestRightwardHeight){
tallestRightwardHeight = y;
}
}
totalWaterTrapped += (Math.min(tallestLeftwardHeight, tallestRightwardHeight) - height[i]);
}
}
return totalWaterTrapped;
}
}
谢谢你的帮助。
答案 0 :(得分:0)
ArrayList#trimToSize
应该是
if (height[x] > tallestLeftwardHeight){
tallestLeftwardHeight = x;
}
和
if (height[x] > tallestLeftwardHeight){
tallestLeftwardHeight = height[x];
}
应该是
if (height[y] > tallestRightwardHeight){
tallestRightwardHeight = y;
}