42. Trapping Rain Water

来源:互联网 发布:excel跨文件数据交互 编辑:程序博客网 时间:2024/05/21 21:34

题目

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 Marcosfor contributing this image!

分析

在给定的柱子高度中找到最大的储水量,由于当前位置能否储水由右侧高度和左侧高度决定,所以先保存每个位置i的右侧最高柱子高度,然后从左向右,记录左侧的最高值,取二者最小为形成的水槽高度,然后与当前的柱子高度比较,如果高度当前高度则能储水,否则不能储水,然后更新左侧最高为左侧最高与当前柱子高度中的最高值,为下一个柱子能否储水考虑。

class Solution {public:    int trap(vector<int>& height) {        if(height.empty())            return 0;        vector<int> right(height.size());//right保存当前位置右侧最大的柱子高度        int n=height.size(), rightMax=height[n-1];        for(int i=n-1;i>=0;--i){            rightMax=max(rightMax,height[i]);            right[i]=rightMax;        }        int leftMax=height[0], res=0;//leftMax保存当前位置左侧最大的柱子高度        for(int i=0;i<n;++i){            int heightMin=min(leftMax,right[i]);//在当前位置形成的水槽是左侧最高和右侧最高之间最小的一个决定的,例如图中[2,1,0,1,3],左侧最高为2,右侧为3,水槽的最终高度是左侧的2决定的,而[3,2,1,2],左侧最高为3,右侧为2,水槽最终高度是右侧的2决定的            res+=heightMin>height[i]?heightMin-height[i]:0;//如果水槽的高度大于当前高度,则差值为水的体积,否则无法形成水槽            leftMax=max(leftMax,height[i]);//更新左侧最高为当前位置最高的        }        return res;    }};


原创粉丝点击