努力调试java解决方案到leetcode算法

时间:2017-04-18 01:35:31

标签: java algorithm debugging

我试图在这里解决这个问题: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;
    }
}

谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

ArrayList#trimToSize

应该是

                if (height[x] > tallestLeftwardHeight){
                    tallestLeftwardHeight = x;
                }

                if (height[x] > tallestLeftwardHeight){
                    tallestLeftwardHeight = height[x];
                }

应该是

                if (height[y] > tallestRightwardHeight){
                    tallestRightwardHeight = y;
                }