Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!Java AC (380 ms)
public class Solution { public int trap(int[] A) { int len = A.length; int max = 0; int lArr[] = new int[len]; for (int i = 0; i < len; i++) { lArr[i] = max; max = Math.max(max, A[i]); } max = 0; int rArr[] = new int[len]; for (int i = len - 1; i >= 0; i--) { rArr[i] = max; max = Math.max(max, A[i]); } int mostWater = 0; for (int i = 0; i < len; i++) { int min = Math.min(lArr[i], rArr[i]); if (min > A[i]) { mostWater += min - A[i]; } } return mostWater; } }2、求解出数组中的最大值,那么从左到最大值index扫描每个点,如果该点左侧最大值比当前点高,就可以装水。同理,从右到最大值index扫描,同样处理。最后累加就是最大值,其实就是1的思路变形。
Java AC (416 ms)
public class Solution { public int trap(int[] A) { if(A == null || A.length == 0){ return 0; } int len = A.length; int maxValue = A[0]; int maxIndex = 0; for(int i = 1; i < len; i++){ if(A[i] > maxValue){ maxValue = A[i]; maxIndex = i; } } int mostWater = 0; int curNum = 0; for(int i = 0; i < maxIndex; i++){ if(curNum > A[i]){ mostWater += curNum - A[i]; }else{ curNum = A[i]; } } curNum = 0; for(int i = len-1; i > maxIndex ; i--){ if(curNum > A[i]){ mostWater += curNum - A[i]; }else{ curNum = A[i]; } } return mostWater; } }