class Solution {
public:
int trap(int A[], int n) {
vector<int> left(n);
int maxheight = 0;
for (int i = 0; i < n; i++)
{
left[i] = maxheight;
maxheight = max(maxheight, A[i]);
}
vector<int> right(n);
maxheight = 0;
for (int i = n - 1; i >= 0; i--)
{
right[i] = maxheight;
maxheight = max(maxheight, A[i]);
}
int result = 0;
for (int i = 0; i < n; i++)
{
int height = min(left[i], right[i]) - A[i];
if (height < 0)
height = 0;
result += height;
}
return result;
}
};
【LeetCode】Trapping Rain Water
最新推荐文章于 2020-08-24 17:46:40 发布