其次,对于每个A[i]能trapped water的容量,取决于A[i]左右两边的高度(可延展)较小值与A[i]的差值,即volume[i] = [min(left[i], right[i]) - A[i]] * 1,这里的1是宽度,如果the width of each bar is 2,那就要乘以2了
publicint(int[] height){ if (height == null || height.length == 0) return0; int[] left = newint[height.length]; int[] right = newint[height.length]; int max, total = 0; max = height[0]; left[0] = height[0]; for (int i = 1; i < height.length; i++) { left[i] = Math.max(max, height[i]); max = Math.max(max, left[i]); } max = height[height.length - 1]; right[height.length - 1] = height[height.length - 1]; for (int i = height.length - 2; i >= 0; i--) { right[i] = Math.max(max, height[i]); max = Math.max(max, right[i]); } for (int i = 1; i < height.length-1; i++) { int bit = Math.min(left[i], right[i]) - height[i]; if (bit > 0) total += bit; } return total; }
近期评论