题目
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.
类似题目,格板储水和美团直方图(栈)
对于每一个格子来说,其左侧的最高板和右侧的最高板决定了水的高度。
所以结合动态规划,分别遍历两次。得到的两个数组分别表示,这个格儿的左侧最高板和右侧最高板儿。
两个值取小,得到答案。
public static int trap(int[] height) {
if (height.length<=2) {
return 0;
}
int[] leftMax = new int[height.length];
int[] rightMax = new int[height.length];
leftMax[0] = height[0];
rightMax[height.length-1] = height[height.length-1];
for (int i = 1; i < height.length-1; i++) {
leftMax[i] = Math.max(leftMax[i-1], height[i]);
rightMax[height.length-i-1] = Math.max(rightMax[height.length-i], height[height.length-i-1]);
}
// System.out.print(Arrays.toString(leftMax));
// System.out.print(Arrays.toString(rightMax));
int container = 0;
for (int i = 1; i<height.length-1; i++) {
int max = Math.min(leftMax[i], rightMax[i]);
container = container+(max-height[i]);
}
return container;
}
不知道为什么代码的字体和发布后的博客代码字体总是不一样,有知道的大佬麻烦留个言。