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!

链接: http://leetcode.com/problems/trapping-rain-water/

题解:

经典题目接雨水。对每个index单独进行考虑,则这个index左侧最高bar与右侧最高bar能组成一个容器,在这个容器里,左侧bar和右侧bar中较低的一个与当前index的差值就为当前index所能储存的雨水量。

Time Complexity - O(n), Space Complexity - O(n)。  可以只使用一个数组,但不如下面代码看起来思路清晰。另外有stack和双指针法,还有待了解。

public class Solution {

    public int trap(int[] height) {

        if(height == null || height.length == 0)

            return 0;

        int sum = 0, max = height[0];

        int[] forward = new int[height.length];

        int[] backward = new int[height.length];

        

        for(int i = 1; i < height.length - 1; i++){

            forward[i] = max;

            max = Math.max(max, height[i]);

        }

        

        max = height[height.length - 1];

        

        for(int i = height.length - 2; i > 0; i--){

            backward[i] = max;

            max = Math.max(max, height[i]);

        }

        

        for(int i = 1; i < height.length - 1; i++){

            int diff = Math.min(forward[i], backward[i]) - height[i];

            if(diff > 0)

                sum += diff;

        }

        

        return sum;

    }

}

测试:

Reference: 

http://www.cnblogs.com/springfor/p/3877101.html

你可能感兴趣的:(water)