42. 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!

分析:能盛多少水取决于短的那个条柱,首先找到最长的那个,这才前后各一个指针才好遍历。

public class Solution {
    public int trap(int[] height) {
        if((height.length == 0) || (height.length==1) || (height.length ==2))
            return 0;
            
        int maxIndex = 0;
        int maxHeight = 0;
        for(int i = 0; i < height.length; ++i) {
            if(maxHeight < height[i]){
                maxHeight = height[i];
                maxIndex = i;
            }
        }
        
        int water = 0;
        int pre = height[0];
        for(int i = 0; i < maxIndex; ++i){
            if(pre < height[i])
                pre = height[i];
            else{
                water += pre-height[i];
            }
        }
        
        int last = height[height.length-1];
         for(int i = height.length-1; i > maxIndex; --i){
            if(last < height[i])
                last = height[i];
            else{
                water += last-height[i];
            }
        }
        
        return water;
        
    }
}

 

posted on 2016-03-15 21:00  菜鸟2s  阅读(168)  评论(0编辑  收藏  举报

导航