首页 > 移动平台 > 详细

42. Trapping Rain Water

时间:2019-06-05 13:50:43      阅读:90      评论:0      收藏:0      [点我收藏+]

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;
    }

42. Trapping Rain Water

原文:https://www.cnblogs.com/reboot329/p/10979017.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!