class Solution {
public:
int trap(vector<int>& height) {
int begin;
int res=0;
for(begin=0;begin<height.size();begin++)//find the first non-zero position
if(height[begin]!=0)
break;
while(begin<height.size())
{
int end,max_idx=begin+1,max=0;
for(end=begin+1;end<height.size();end++)//find the end position of the container
{
if(height[end]>=height[begin])
{
break;
}
if(height[end]>max)//mark the position with the maximum height
{
max=height[end];
max_idx=end;
}
res+=height[begin]-height[end];
}
if(end!=height.size())//exists the end position with the height greater than or equal to the begin position
begin=end;
else//end height is smaller than the begin position, subtract the heights after the max_idx and the redundant height before it
{
for(int i=max_idx;i<end;i++)
res-=height[begin]-height[i];
res-=(max_idx-begin-1)*(height[begin]-max);
begin=max_idx;
}
}
return res;
}
};
leetcode 42: Trapping Rain Water
最新推荐文章于 2022-01-16 12:23:12 发布