LeetCode---(42)Trapping Rain Water

来源:互联网 发布:vba数组可否使用clear 编辑:程序博客网 时间:2024/05/17 05:06

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!

题意为:

给定N个非负整数,表示直方图的方柱的高度,同时,每个方柱的宽度假定都为1,若使用这样形状的容器收集雨水,可以盛多少水量?

思路:

记录最终盛水量为trap,初值为0;

考察直方图最左边L和最右边R两个方柱:

他们两个本身,一定不可能存储雨水,因为在最边界;

记他们比较低的那个为X,与X相邻的方柱记为Y.

若Y>=X,可将X丢弃,且trap值不变;

若Y<x,则X-Y即为Y方柱最多盛水量,仍然丢弃X,并且trap+=(X-Y);

无论如何,L或R都将向中间靠近一步,重复上述过程,直至L==R

解法:

class Solution {public:    int trap(vector<int>& height) {        int secHight=0;     //当前找到的第二大的数        int left=0;        int right=height.size()-1;        int result;        while(left<right)        {            if(height[left]<height[right])            {                secHight=max(height[left],secHight);                result+=(secHight-height[left]);                left++;            }            else{                secHight=max(height[right],secHight);                result+=(secHight-height[right]);                right--;            }        }        return result;    }};




0 0
原创粉丝点击