找到数组中从下标 i 到最左端最高的条形块高度left_max。
找到数组中从下标 i 到最右端最高的条形块高度 right_max。
扫描数组height 并更新答案:
累加 min(max_left[i],max_right[i])−height[i] 到 ans 上
class Solution {
public:
int trap(vector<int>& height) {
int size=height.size(),ans=0;
vector<int>left_max(size),right_max(size);
left_max[0]=height[0];
for(int i=1;i<size;++i){
left_max[i]=max(left_max[i-1],height[i]);
}
right_max[size-1]=height[size-1];
for(int i=size-2;i>=0;--i){
right_max[i]=max(right_max[i+1],height[i]);
}
for(int i=1;i<size-1;++i){
ans+=min(left_max[i],right_max[i])-height[i];
}
return ans;
}
};
双指针
class Solution {
public:
int trap(vector<int>& height) {
int left=0,right=height.size()-1;
int left_max=0,right_max=0,ans=0;
while(left<right){
if(height[left]<height[right]){
if(height[left]<left_max) ans+=(left_max-height[left]);
else left_max=height[left];
++left;
}
else{
if(height[right]<right_max) ans+=(right_max-height[right]);
else right_max=height[right];
--right;
}
}
return ans;
}
};