42. Trapping Rain Water

June-4-2019
蓄水池,双指针的应用。复习一下就是每次只能选一个指针来单向运动。这个题我居然没记录过。

这里个题需要同时维护左右两边的木板高度,通过木板高度来判断移动哪边的指针,移动较短的那边。移动的双指针干3件事:

  • 看有没有更高的木板,有就记下来
  • 看能不能以较小的木板为边界蓄水(上面那种情况不行。。)
  • 没了
    public int trap(int[] height) {
        int res = 0;
        if (height.length < 2) return res;
        
        int l = 0;
        int r = height.length - 1;
        int lHeight = height[l];
        int rHeight = height[r];
        while (l < r) {
            if (lHeight < rHeight) {
                if (l + 1 != r && lHeight > height[l + 1]) {
                    res += lHeight - height[l + 1];
                }
                lHeight = Math.max(lHeight, height[++l]);
            } else {
                if (r - 1 != l && rHeight > height[r - 1]) {
                    res += rHeight - height[r - 1];
                }
                rHeight = Math.max(rHeight, height[--r]);
            }
        }
        
        return res;
    }
原文地址:https://www.cnblogs.com/reboot329/p/10979017.html