[LeetCode]042-Trapping Rain Water

来源:互联网 发布:安能 淘宝 编辑:程序博客网 时间:2024/05/29 10:51

题目:
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!

Solution:
思路,先找到最高的点,然后两边处理。举例左边的情况:
设置两个指针i,j。i往中间最高点移动,若height[i] >=height[j]。则计算j和i之间的可存放空间,并将j移动到i的位置:j=i,i继续往后移动,直到最高点。右边的处理情况类似。
代码如下:

class Solution {public:    int trap(vector<int>& height)    {        int n = height.size();        int i,j,k;        int sum = 0;        int h = 0;        int max = 0;        for(i =0;i<n;i++)        {            if(height[i] > max)            {                max = height[i];                h = i;            }        }        i = 0;        j = i+1;        while(i<=h && j <=h)        {            if(height[i] >=  height[j])            {                sum += calculate(height,j,i);                j = i;            }            i++;        }        j=n-1;        i = j-1;        while(i >= h)        {            if(height[i] >=  height[j])            {                sum += calculate(height,i,j);                j = i;            }            i--;        }        return sum;    }    int calculate(vector<int> height,int begin,int end)    {        int h = min(height[begin],height[end]);        int w = end - begin-1;        int area = h * w;        for(int i = begin+1;i<end;i++)        {            area -= height[i];        }        return area<0?0:area;    }};
0 0
原创粉丝点击