Trapping Rain Water

Q:

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!

 

A:

题目相当的经典,先找到最高点h,然后从最高点h向左找该点左边的最高点l,算出两点之间能容纳的水量,然后将h置为l,继续找l左边的最高点,一直找到l为0为止。

用同样的方法从h向右找。

好了,方法知道了,很明显,我们如果知道了每个点左边的最高点以及右边的最高点,这个题就很easy了。

时间复杂度o(n), 空间复杂度o(n)

class Solution {
public:
    int trap(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (n <= 2) return 0;
        int result = 0;
        int* highest_pos_l = new int[n];
        int* highest_pos_r = new int[n];
        highest_pos_l[0] = 0;
        for (int i = 1; i < n; ++i) {
            highest_pos_l[i] = A[highest_pos_l[i - 1]] >= A[i - 1] ? highest_pos_l[i - 1] : i - 1;
        }
        highest_pos_r[n - 1] = n - 1;
        for (int i = n - 2; i >=0; --i) {
            highest_pos_r[i] = A[highest_pos_r[i + 1]] >= A[i + 1] ? highest_pos_r[i + 1] : i + 1;
        }
        int highest_pos = A[highest_pos_r[0]] > A[0] ? highest_pos_r[0] : 0;
        int left_pos = highest_pos_l[highest_pos];
        int right_pos = highest_pos_r[highest_pos];
        int pre_pos = highest_pos;
        while (pre_pos != 0) {
            for (int i = pre_pos - 1; i > left_pos; --i) {
                result += A[left_pos] - A[i];
            }
            int tmp = pre_pos;
            pre_pos = left_pos;
            left_pos = highest_pos_l[tmp];
        }
        pre_pos = highest_pos;
        while (pre_pos != n - 1) {
            for (int i = pre_pos + 1; i < right_pos; ++i) {
                result += A[right_pos] - A[i];
            }
            int tmp = pre_pos;
            pre_pos = right_pos;
            right_pos = highest_pos_r[tmp];
        }
        delete [] highest_pos_l;
        delete [] highest_pos_r;
        return result;
    }
};

 

posted @ 2013-06-16 21:18  dmthinker  阅读(114)  评论(0)    收藏  举报