classSolution{ publicinttrap(int[] height){ int n = 0; for (int i = 0; i < height.length; i++) { int max = getMax(height, i); int i1 = height[i]; if (max > i1) { n += max - i1; } } return n; }
/** * 获取i位置的左右两侧的最大值,取出最大值中的最小值 */ publicintgetMax(int[] height, int i){ if (i <= 0 || i >= height.length - 1) { return0; } int leftMax = -1, rightMax = -1; //获取左边最大值 for (int j = i - 1; j >= 0; j--) { int i1 = height[j]; if (i1 > leftMax) { leftMax = i1; } } //获取右边最大值 for (int j = i + 1; j < height.length; j++) { int i1 = height[j]; if (i1 > rightMax) { rightMax = i1; } } return Math.min(leftMax, rightMax); } }