LeetCode 42 Trapping Rain Water

Trapping Rain Water

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!

Subscribe to see which companies asked this question

解题思路:从这个网址上学到一个思想,http://blog.unieagle.net/2012/10/31/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Atrapping-rain-water/

决定一个水槽的容积为两个左右的高度,并取决于两者的最小高度。对于数组每个元素来讲,我们可以求出两个这样的高度,最后相加其最小。那么,我们考虑只考虑一个单边,以左边为例,从左边开始遍历其相对于已有的最高高度的高度差即为单边的高度。右边亦然,两者最小求和,即为总的容积。

从左边开始遍历,记录相对于已有的最高值的差值。同时,从右边开始遍历记录相对于右边已有的最高值的差值。

 public int trap(int[] height) {
    	int len = height.length;
    	if(len<=2)return 0;
    int [] test = new int[len+1];
    int max = 0;
    int sum = 0;
   for (int i = 0; i < len; i++) {
	   test[i]=max-height[i]>0?max-height[i]:0;
     	if(height[i]>max){
     		max = height[i];
     	}     	
}
    max = 0;
    int temp =0;
   for (int i = len-1; i > 0; i--) {
	   temp = max-height[i]>0?max-height[i]:0;
	   sum += temp>test[i]?test[i]:temp;
    	if(height[i]>max){
    		max = height[i];
    	}  
}
        return sum;
    }






你可能感兴趣的:(LeetCode 42 Trapping Rain Water)