LeetCode(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!

分析

思路参考

AC代码

class Solution {
public:
    int trap(vector<int>& height) {
        if (height.empty())
            return 0;

        int len = height.size();

        int lhs = 0, rhs = len - 1, secHeight = 0;

        int area = 0;

        //从两边向中间统计,分别统计每个竖立格子可以盛的水量
        while (lhs < rhs)
        {
            if (height[lhs] < height[rhs])
            {
                secHeight = max(height[lhs], secHeight);
                //加上lhs竖格的盛水量
                area += secHeight - height[lhs];
                //左侧右移一格
                lhs++;
            }
            else{
                secHeight = max(height[rhs], secHeight);
                //加上rhs竖格的盛水量
                area += secHeight - height[rhs];
                //右侧左移一格
                rhs--;
            }//fi
        }//while

        return area;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214832.html