一、前言
给定一个数组[0,1,2,1,4,3,6,4…],数组元素代表每根柱子的高度,每根柱子宽度为1,问柱子缝隙中所能接住的雨水面积是多少?
二、算法思路
每根柱子左右两边的最大高度记为Lmax和Rmax,当前柱子高度记为height[i],每根柱子所能盛住的雨水面积为(Min(Lmax, Rmax)-height[i])*1
三、算法Java实现
public class Solution {
/**
* @param heights: a list of integers
* @return: a integer
*/
public int trapRainWater(int[] heights) {
// write your code here
if(heights == null || heights.length == 0 || heights.length <= 2){
return 0;
}
int leftMax = heights[0], rightMax = heights[heights.length-1];
int i = 1, j = heights.length-2;
int result = 0;
int increment = 0;
while(i <= j) {
leftMax = Math.max(leftMax, heights[i - 1]);
rightMax = Math.max(rightMax, heights[j + 1]);
if(leftMax <= heights[j+1]
&& (increment = leftMax - heights[i++]) > 0){
result += increment;
}else if(rightMax <= heights[i-1] && (increment = rightMax - heights[j--]) > 0){
result += increment;
}
}
return result;
}
}