标签:eth width height generate sys bsp todo cap info
描述
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute
how much water it is able to trap after raining.
For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6
分析
对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,
max_right) - height。所以
1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
2. 从右往左扫描一遍,对于每个柱子,求最大右值;
3. 再扫描一遍,把每个柱子的面积并累加。
也可以,
1. 扫描一遍,找到最高的柱子,这个柱子将数组分为两半;
2. 处理左边一半;
3. 处理右边一半。
代码
1 package StacksAndqueues; 2 3 public class TrappingRainWater { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 //从左往右找到最大,再从右到左找到最大,目前最大-目前array[i];找到其中最小的,即为存水量。 8 int[] array= {0,1,0,2,1,0,1,3,2,1,2,1}; 9 System.out.println(trap(array)); 10 } 11 12 public static int trap(int[] array) { 13 if (array.length == 0) 14 return 0; 15 int len = array.length - 1; 16 int[] maxl = new int[len + 1]; 17 int[] maxr = new int[len + 1]; 18 int cap = 0, total = 0; 19 for (int i = len; i >= 0; i--) { 20 maxr[i] = cap; 21 if (array[i] > cap) 22 cap = array[i]; 23 } 24 cap = 0; 25 for (int i = 0; i <= len; i++) { 26 maxl[i] = cap; 27 if (array[i] > cap) 28 cap = array[i]; 29 } 30 for (int i = 0; i <= len; i++) { 31 int c = Math.min(maxl[i], maxr[i]) - array[i]; 32 if (c > 0) 33 total += c; 34 } 35 return total; 36 } 37 }
标签:eth width height generate sys bsp todo cap info
原文地址:https://www.cnblogs.com/ncznx/p/9281755.html