【leetcode】Array——Trapping Rain Water(42)

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.



解题:

第一次尝试,一层一层找,虽然算法没错 但是time out了

网上资料:

找到制高点,然后分别从两端往中间遍历。

遍历的过程中记录局部的最高点,当前高度与局部最高点之间的差值就是当前位置的水量。



代码如下:

	public int trap(int []height){
		
		if(height.length<=2)
			return 0;
		
		//get max height
		int max_height = height[0];
		int max_index = 0;
		for(int i=0;i<height.length;i++){
			if(max_height<=height[i]){
				max_height = height[i];
				max_index=i;
			}
		}
		
		int result=0;
		
		int jubu_max_l=height[0];
		for(int i=1;i<max_index;i++){
			if(height[i]>=jubu_max_l)
				jubu_max_l = height[i];
			else
				result += (jubu_max_l-height[i]);
		}
		int jubu_max_r =height[height.length-1];
		for(int i=height.length-2;i>max_index;i--){
			if(height[i]>=jubu_max_r)
				jubu_max_r=height[i];
			else
				result += (jubu_max_r-height[i]);
		}
		
		return result;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值