Trapping Rain Water
阿新 • • 發佈:2018-07-09
where and == app trapping code println pin 最大值
描述
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 }
Trapping Rain Water