【LeetCode】Trapping Rain Water 2013年美团网校园招聘研发工程师笔试题

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.


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!

Discuss

java code :   lhs 对应能装水的台阶的左边界,rhs对应右边界,在这个边界确定的范围内,对每一个A[i] ,其能装到的水的大小为 min{左边最高值 ,右边界最高值} - A[i]  if ( 该值 > A[i]) .我们预处理出这样一个左边界的最高值数组
lheight[] ,然后从右边扫过来即可。算法的复杂度是O(n)。
public class Solution {
    public int trap(int[] A) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int length = A.length;
		 if(length <= 2)
			 return 0;
		 int lhs = 0, rhs = length - 1;
		 while((lhs + 1) < length)
		 {
			 if(A[lhs + 1] >= A[lhs])
				 lhs++;
			 else break;
		 }
		 while(rhs > 0)
		 {
			 if(A[rhs - 1] >= A[rhs])
				 rhs--;
			 else break;
		 }
		 int[] lheight = new int[length];
		 int maxheight = A[lhs];
		 for(int i = lhs + 1; i < rhs; i++)
		 {
			 lheight[i] = maxheight;
			 if(A[i] > maxheight)
				 maxheight = A[i];
		 }
		 maxheight = A[rhs];
		 int res = 0;
		 for(int i = rhs - 1; i > lhs; i--)
		 {
			 int minheight = Math.min(maxheight, lheight[i]);
			 if(minheight > A[i])
				 res += minheight - A[i];
			 if(A[i] > maxheight)
				 maxheight = A[i];
		 }
		 lheight = null;
		 return res;
        
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值