Trapping Rain Water

来源:互联网 发布:明源软件股份有限公司 编辑:程序博客网 时间:2024/06/11 23:38

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!

class Solution {public:    /**     * @param heights: a vector of integers     * @return: a integer     */    int trapRainWater(vector<int> &heights) {        // write your code here        int n = heights.size();        if (n < 1)        {            return 0;        }        int result = 0;        int rightMax[n];        rightMax[n-1] = heights[n-1];        for (int i = n-2; i >= 0; i--)        {            if (heights[i] > rightMax[i+1])            {                rightMax[i] = heights[i];            }            else            {                rightMax[i] = rightMax[i+1];            }        }        int begin = 0;        while (begin < n && heights[begin] == 0)        {            begin++;        }        for (int i = begin+1; i < n; i++)        {            if (heights[i] >= heights[begin] || heights[i] == rightMax[i])            {                int top = min(heights[i], heights[begin]);                for (int j = begin+1; j < i; j++)                {                    if (heights[j] < top)                    {                        result += (top - heights[j]);                    }                }                begin = i;            }        }        return result;    }};



0 0