2015年6月21日星期日

Trapping Rain Water leetcode

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!
对于位置i可蓄水量取决于他的左右侧高度的较小值与height[i]的差值, 所以只要找到i的左侧的短板和右侧短板 
从左到右遍历一遍找到左侧的短板 再从右到左便利一次找到右边的短板
一共遍历三次 时间O(n) 空间 O(n)

public class Solution {
    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int len = height.length;
        int[] left = new int[len];
        int[] right = new int[len];
        int leftmax = height[0];
        int rightmax = height[len - 1];
        for (int i = 1; i < len; i ++) {
            left[i] = Math.max(leftmax, height[i]);
            leftmax = Math.max(leftmax, height[i]);
        }
        for (int j = len - 2; j >= 0; j--) {
            right[j] = Math.max(rightmax, height[j]);
            rightmax = Math.max(rightmax, height[j]);
        }
        int res = 0;
        for (int i = 0; i < len; i ++) {
            int tem = Math.min(left[i], right[i]) - height[i];
            if (tem > 0) {
                res += tem;
            }
        }
        return res;
    }
}

没有评论:

发表评论