动态规划法
class Solution {
public:
int trap(vector<int>& height) {
size_t len = height.size();
vector<int> leftMax(len);
vector<int> rightMax(len);
leftMax[0] = height[0];
for(int i = 1;i < len;i++)
{
leftMax[i] = max(leftMax[i-1],height[i]);
}
rightMax[len-1] = height[len-1];
for(int i = len -2;i >=0;i--)
{
rightMax[i] = max(rightMax[i+1],height[i]);
}
int temp = 0;
int res = 0;
for(int i = 0;i < len;i++)
{
temp = min(leftMax[i],rightMax[i]) - height[i];
if(temp > 0) res += temp;
}
return res;
}
};
双指针法
class Solution {
public:
int trap(vector<int>& height) {
int res = 0;
size_t len = height.size();
int left = 0;
int right = len - 1;
int leftMax = 0;
int rightMax = 0;
while(left <= right)
{
leftMax = max(height[left],leftMax);
rightMax = max(height[right],rightMax);
if(leftMax < rightMax)
{
if(leftMax - height[left] > 0)
res+= leftMax - height[left];
left++;
}
else
{
if(rightMax - height[right] > 0)
res += rightMax - height[right];
right--;
}
}
return res;
}
};