42. Trapping Rain Water
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!
解析
- 找到最高水位,然后记录左边最大水位,低于最大水位就累加,从最右边记录最高水位,低于水位就累加!
// add 42. Trapping Rain Water
class Solution_42 {
public:
// 本来自己想用总面积-黑色块的面积,但是总面积不容易求得
// 思路1:找到最高的柱子,分左右两边处理
int trap(vector<int>& height) {
if (height.size()<=0)
{
return 0;
}
int max_index = 0;
int max_height = height[0];
for (int i = 1; i < height.size();i++)
{
if (height[i]>max_height)
{
max_height = height[i];
max_index = i;
}
}
int sum = 0;
int max_left = 0;
for (int i = 0; i < max_index;i++)
{
if (height[i]>max_left)
{
max_left = height[i];
}
else
{
sum += (max_left-height[i]);
}
}
int max_right = 0;
for (int i = height.size() - 1; i >max_index; i--)
{
if (height[i]>max_right)
{
max_right = height[i];
}
else
{
sum += (max_right-height[i]);
}
}
return sum;
}
int trap(int A[], int n) {
vector<int > vec(A,A+n);
return trap(vec);
}
};
题目来源
C/C++基本语法学习
STL
C++ primer