本人菜鸡,参照评论大佬得解;第一个容易理解,第二个动态规划
int trap(vector<int> &height)
{
int len = height.size();
if (len == 0)
return 0;
int maxIndex = 0; //最高点
int res = 0;
//找出最高点索引
for (int i = 0; i < len; i++)
{
if (height[i] > height[maxIndex])
maxIndex = i;
}
//从左端点向最高点遍历
int temp = 0;
for (int cur = 0; cur < maxIndex; cur++)
{
if (height[cur] >= temp)
temp = height[cur];
else
{
res += temp - height[cur];
}
}
//从右端点向最高点遍历
temp = 0;
for (int cur = len - 1; cur > maxIndex; cur--)
{
if (height[cur] > temp)
temp = height[cur];
else
{
res+=temp-height[cur];
}
}
return res;
}