42. Trapping Rain Water

比11题更加复杂,多了两个变量lm, rm分别用来指代左边的最大高度和右边的最大高度,相当于11题的height[i], height[j]。在大循环i < j中,当lm < rm时,i向左边移动去试探有没有更大的高度,同时水以左边墙壁的最大值为基准增加lm - height[i],右边相反。

public int trap(int[] height) {
    int result = 0;
    int lm = 0, rm = 0;
    int i = 0, j = height.length - 1;
    while (i < j) {
        lm = Math.max(lm, height[i]);
        rm = Math.max(rm, height[j]);
        if (lm < rm) {
            result += lm - height[i];
            i++;
        } else {
            result += rm - height[j];
            j--;
        }
    }
    return result;
}

results matching ""

    No results matching ""