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
.
思路:可以找到每个元素左边和右边最大的,当前bar可以装的大小即为min(max_left,max_right) - height[i]
前提是min(max_left,max_right) < height[i]
有两种方法,第一种比较粗暴,对每个元素分别找出左边最大,右边最大的时间复杂度O(n),空间复杂度O(n)
第二种,先找出所有元素中最大的,然后在两边分别分别处理,时间复杂度O(n),空间复杂度O(1)
AC1:
class Solution {
public:
int trap(vector<int>& height)
{
int result = 0;
int size = height.size();
if (size == 0)
return result;
if (size == 3)
return (min(height[0],height[2]) - height[1]) > 0 ? (min(height[0],height[2]) - height[1]) : 0;
vector<int> max_left;
vector<int> max_right;
int max = height[0];
max_left.push_back(max);
//计算每个元素左边最大的
for (int i = 1; i < size - 2; i++)
{
max = max > height[i] ? max : height[i];
max_left.push_back(max);
}
//计算每个元素右边最大的
max_right.push_back(height[size - 1]);
max = height[size - 1];
for (int i = size - 2; i > 1; i--)
{
max = max > height[i] ? max : height[i];
max_right.push_back(max);
}
//计算result
for (int i = 0; i < size - 2; i++)
{
int temp = min(max_left[i],max_right[size - 3 - i]) - height[i + 1];
if (temp > 0)
result += temp;
}
return result;
}
};
class Solution {
public:
int trap(vector<int>& height)
{
int result = 0;
int size = height.size();
if (size < 3)
return result;
if (size == 3)
return (min(height[0],height[2]) - height[1]) > 0 ? (min(height[0],height[2]) - height[1]) : 0;
//找出最高的
int max_index = 0;
for (int i = 1; i < size; i++)
if (height[i] > height[max_index])
max_index = i;
//搜索左边
for (int i = 1,peak = 0; i < max_index; i++)
{
if (height[i] > height[peak])
peak = i;
else
result += height[peak] - height[i];
}
//搜索右边
for (int i = size - 2,peak = size - 1; i > max_index; i--)
{
if (height[i] > height[peak])
peak = i;
else
result += height[peak] - height[i];
}
return result;
}
};