C++提交:
执行用时 :8 ms, 在所有 C++ 提交中击败了60.63%的用户
内存消耗 :6.8 MB, 在所有 C++ 提交中击败了100.00%的用户
算法思路:当前位置所能接到的水取决于其左边所有柱子的最大高度和右边柱子的最大高度。
// C++ Version
int trap(vector<int>& height) {
int res=0;
if(height.size()<=2)//柱子数目低于3时,不能接到水
return res;
int cursor=0;
int begin=height[0],end=-1;//保存当前节点左右柱子的最大高度
for(int a=2;a<height.size();a++)//初始化右边柱子的最大高度
end=max(end,height[a]);
for(int a=1;a<height.size()-1;a++){
begin=max(begin,height[a-1]);//左边所有柱子的最大高度只需要在每一次迭代之前更新即可。
if(height[a]!=end)//如果当前节点的高度与右边所有柱子的最大高度不同,则不需要更新,因为最大高度肯定在右边
goto L1;
cursor=a+1;
end=height[cursor];
while(cursor<height.size()){end=max(end,height[cursor++]);}
L1:
if(min(begin,end)>height[a])
res+=min(begin,end)-height[a];
}
return res;
}