package leecode; /** * Created by root on 17-6-16. */ public class TrappingRainWater { /* 这个题的核心在于比对左侧最大和右侧最大,如果左侧最大小于右侧最大,左侧的右临才有灌水的可能,还要取决最大值的位置是否是当前访问的位置。 因此,加入的水就等于max与当前bar的差值,这个值最小为0,不为0说明有水灌入 同理右侧也是一样。 */ public int trap(int[] height) { int letfmax = 0, rightmax = 0; int a = 0, b = height.length - 1; int sum = 0; while (a <= b) { letfmax = Math.max(letfmax, height[a]); rightmax = Math.max(rightmax, height[b]); if (letfmax < rightmax) { sum += letfmax - height[a]; a++; } else { sum += rightmax - height[b]; b--; } } return sum; } }
42. Trapping Rain Water
最新推荐文章于 2021-02-07 14:36:30 发布