41. 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. 

---

对于任何一个坐标,检查其左右的最大坐标,然后相减就是容积。所以,
1. 从左往右扫描一遍,对于每一个坐标,求取左边最大值。
2. 从右往左扫描一遍,对于每一个坐标,求最大右值。
3. 再扫描一遍,求取容积并加和。
#2和#3可以合并成一个循环,

---

1. 分开的循环

public class Solution {
    public int trap(int[] A) {

        int res = 0;

        // at least len = 3 to be container
        if (A.length < 3)    return res;

        int n = A.length;
        int[] leftMax = new int[n];
        int[] rightMax = new int[n];

        // store the max value on the lest
        int max = 0;
        for (int i = 0; i < n; i++) {
            leftMax[i] = max;
            if (A[i] > max)    max = A[i];
        }

        // store the max value on the right
        max = 0;
        for (int i = n - 1; i >= 0; i--) {
            rightMax[i] = max;
            if (A[i] > max)    max = A[i];
        }

        for (int i = 1; i < n - 1; i++) {
            int tmp = Math.min(leftMax[i], rightMax[i]);
            if (tmp > A[i])    res += tmp - A[i];
        }

        return res;
    }
}

2-3合并

 

public class Solution {
    public int trap(int[] A) {

        int res = 0;

        // at least len = 3 to be container
        if (A.length < 3)    return res;

        int n = A.length;
        int[] leftMax = new int[n];
        int[] rightMax = new int[n];

        // store the max value on the lest
        int max = 0;
        for (int i = 0; i < n; i++) {
            leftMax[i] = max;
            if (A[i] > max)    max = A[i];
        }

        // store the max value on the right
        max = 0;
        for (int i = n - 1; i >= 0; i--) {
            rightMax[i] = max;
            if (A[i] > max)    max = A[i];
            
            
            // could contain water?
            if(i < n-1 && i > 0){
                int tmp = Math.min(leftMax[i], rightMax[i]);
                if (tmp > A[i])    res += tmp - A[i];    
            }
            
        }

        return res;
    }
}

 

 

posted @ 2013-09-06 02:11  LEDYC  阅读(174)  评论(0)    收藏  举报