1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| public class leetcode_trapping_rain_water_kgh { public static void main(String[] args) { trap(new int[]{0,1,0,2,1,0,1,3,2,1,2,1}); trap(new int[]{0,0,0,0,1,0,1,3,2,1,0,0}); trap(new int[]{1,0,1,1,1,0,1,0,2,1,1,1}); } static int trap(int[] height) {
int minIdx = 0; int maxIdx = 0; boolean isMax = false; boolean isMin = false; for(int i=0; i<height.length; i++){ if(height[i] == 0){ isMin = true; }else { if(isMin){ minIdx = i; break; } else { minIdx = Math.min(minIdx, i); break; } } }
for(int i=height.length-1; i >= 0; i--){ if(height[i] == 0){ maxIdx = i; isMax = true; }else { if(isMax){ maxIdx = i; break; } else { maxIdx = Math.max(maxIdx, i); break; } } } System.out.println(minIdx + " " + maxIdx); int maxHightIdx = 0; for(int i=0; i<height.length; i++){ if(height[i] > height[maxHightIdx]){ maxHightIdx = i; } } int h = 0; int leftSum = 0; int sum = 0; for(int i=minIdx; i<maxHightIdx; i++){ leftSum += height[i]; h = Math.max(height[i], h); sum += h; } h = 0; int rightSum = 0; for(int i=maxIdx; i>maxHightIdx; i--){ rightSum += height[i]; h = Math.max(height[i], h); sum += h; } System.out.println(sum + " " + leftSum + " "+ rightSum); return sum-(leftSum + rightSum); } }
|