您的位置:首页 > 移动开发

LeetCode:Trapping Rain Water

2014-04-09 10:08 405 查看


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
.



看到这个题目,A[I]存储的水量主要取决于其左边最大值和右边最大值两个值的最小值minh,如果A[I]<minh,则存储水量为minh-A[i].因此想到用一个数组记录A[I]左边所有值的最大值,从右边往左边加过去,最终返回存储水量。
public class Solution {
public int trap(int[] A) {
if(A.length<=2)return 0;
int [] leftMaxHeight=new int[A.length];
leftMaxHeight[0]=0;
int maxh=A[0],len=A.length;
for(int i=1;i<A.length;i++)
{
leftMaxHeight[i]=maxh;
if(maxh<A[i])maxh=A[i];
}

int right=A[len-1],left,sum=0;
for(int i=len-2;i>0;i--)
{
left=leftMaxHeight[i];
int minh=Math.min(right,left);
if(minh>A[i])sum+=minh-A[i];
if(right<A[i])right=A[i];

}
return sum;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息