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

LeetCode 第四十二题(Trapping Rain Water) Java

2016-11-07 21:07 447 查看
原题: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
.







这道题我听过左程云老师的解法,能达到时间复杂度O(n),空间复杂度O(n);

要求这样一个容器能容纳多少水,可以求对于该容器每个位置(即第 i 列)能容纳多少水;

第 i 列能盛下的水等于 i 位置左边最高的值,和右边最高的值的最小值。减去 i 位置的高度,若大于0则可以盛水;

所以该题需要求某位置左边最小值和右边最小值;

先反向遍历一遍,求右边最小值数组;

再从左遍历,用一个值记录左边最小值,依次遍历,得到整个容器的盛水数量

代码:

public class Solution {
public int trap(int[] height) {
if(height.length<3){
return 0;
}
int[] maxOfRight=new int[height.length];//记录右边的最大值;
//int maxRight=0;
maxOfRight[height.length-1]=height[height.length-1];
for(int i=height.length-2;i>=0;i--){
//某位置右边最大的(这道题可以包括该位置)就是找该位置后一位右边最大的与该位置的值比较;
maxOfRight[i]=Math.max(maxOfRight[i+1],height[i]);
}

int maxOfLeft=height[0];
int sum=0;
int store=0;
for(int i=1;i<height.length;i++){
maxOfLeft=maxOfLeft>height[i]?maxOfLeft:height[i];
store=Math.min(maxOfLeft,maxOfRight[i])-height[i];
store=store>0?store:0;
sum+=store;
}
return sum;
}
}我现在有一点问题在于即使想到算法,在编程时以及对边界的处理时经常出错误,如果有好的建议,也请大家不吝赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: