Trapping Rain Water

来源:互联网 发布:淘宝怎么开发票 编辑:程序博客网 时间:2024/05/17 01:52

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]来说,能trapped的最多的water取决于在i左边的最高的值leftHeight[i]和

在i右边的最高的值rightHeight[i]。那么在i这个位置上能trapped的water就是

min(left,right) – A[i]。有了这个想法就好办了,第一遍从左到右计算数组leftHeight,

第二遍从右到左计算rightHeight。时间复杂度是O(n)。

public class Solution {    public int trap(int[] height) {        int result=0,maxHeight=0;if(height==null||height.length<=2)return result;int[] left=new int[height.length];int[] right=new int[height.length];left[0]=maxHeight=height[0];for(int i=1;i<height.length;i++){maxHeight=maxHeight>height[i]?maxHeight:height[i];left[i]=maxHeight;}right[height.length-1]=maxHeight=height[height.length-1];for(int i=height.length-2;i>=0;i--){maxHeight=maxHeight>height[i]?maxHeight:height[i];right[i]=maxHeight;}for(int i=0;i<height.length;i++)result+= Math.min(left[i],right[i])-height[i];return result;    }}



0 0
原创粉丝点击