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
| package algorithm;
public class TrappingRainWater {
// 凹形槽的两个条件:一个是往右找,比自己高的,那就停止;一个是找最近接自己高度的 // 也就是第二高的,记录位置 public static int trap(int[] height) {
int left = 0; int right = 1; int area = 0;
while (right < height.length && left < right) { if (height[left] < height[right]) { left++; right = left + 1; continue; } int tempMax = right; while (right < height.length && height[left] > height[right]) { if (height[right] > height[tempMax]) { tempMax = right; } right++; } if (right < height.length && height[right] > height[tempMax]) { tempMax = right; } int minHeight = Math.min(height[left], height[tempMax]); for (int i = left + 1; i < tempMax; i++) { area += minHeight - height[i]; } left = tempMax; right = left + 1; }
return area; }
public static int trap1(int[] height) { int left = 0; int right = height.length - 1; int leftMax = 0; int rightMax = 0; int ans = 0;
while (left < right) { if (height[left] < height[right]) { if (height[left] >= leftMax) { leftMax = height[left]; } else { ans += leftMax - height[left]; } left++; } else { if (height[right] >= rightMax) { rightMax = height[right]; } else { ans += rightMax - height[right]; } right } }
return ans; }
public static void main(String[] args) { int[] height = new int[]{0,1,0,2,1,0,1,3,2,1,2,1}; System.out.println(trap1(height));
height = new int[]{4,2,0,3,2,5}; System.out.println(trap1(height));
height = new int[]{4,2,3}; System.out.println(trap1(height)); } }
|