您的位置:首页 > 移动开发

[LeetCode]042-Trapping Rain Water

2015-12-29 19:06 495 查看
题目:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode