Description:
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.
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!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
题意:给定一串数组代表连续的柱子的高度,默认宽度为1,要求计算下雨后,这些柱子之间能够装下多少的水;
解法一:两个柱子之间能够装下多少的水,取决于最短的那根柱子,并且至少有三根柱子才有可能装下水,因此,我们可以对于每一根柱子找到他的左边与右边最长的那根柱子,所能装下水的容量就是左右边最长中较短的那根与这根柱子的差值;
class Solution {
public int trap(int[] height) {
if(height.length <= 2){
return 0;
}//It cant't hold water when the columns less than two
int holdWater = 0;
for(int i=1; i<height.length-1; i++){
int maxLeft = 0;
int maxRight = 0;
for(int j=i; j>=0; j--) maxLeft = Math.max(maxLeft, height[j]);
for(int j=i; j<height.length; j++) maxRight = Math.max(maxRight, height[j]);
holdWater += Math.min(maxLeft, maxRight) - height[i];
}
return holdWater;
}
}
解法二:在第一种的解法中,对于每一根的柱子我们都需要找到其左边与右边的柱子的最大高度,其中的大部分计算都是重复的,基于动态规划的思想,我们可以将每次计算的结果存储下来,而不需要每次都计算;
class Solution {
public int trap(int[] height) {
if(height.length <= 2){
return 0;
}//It cant't hold water when the columns less than two
int[] maxLeft = new int[height.length];
int[] maxRight = new int[height.length];
maxLeft[0] = height[0];
maxRight[height.length-1] = height[height.length-1];
for(int i=1; i<height.length; i++) maxLeft[i] = Math.max(height[i], maxLeft[i-1]);
for(int i=height.length-2; i>=0; i--) maxRight[i] = Math.max(height[i], maxRight[i+1]);
int holdWater = 0;
for(int i=1; i<height.length-1; i++){
holdWater += Math.min(maxLeft[i], maxRight[i]) - height[i];
}
return holdWater;
}
}