42. 接雨水
代码:
int trap(vector<int>& height) {
int sum=0,min=0,max=0;
int i=0,j=height.size()-1;
while(i<j){
//while(height[i]<height[i+1]) i++;
//while(height[j]<height[j-1]) j--;
while (i < j && i + 1 < height.size() && height[i] < height[i + 1]) i++;
while (i < j && j - 1 >= 0 && height[j] < height[j - 1]) j--;
if(i>=j)break;
if(height[i]>height[j]){
max=height[i];min=height[j];j--;
//cout<<"左大 i:"<<i<<" j:"<<j<<" min:"<<min<<" max:"<<max<<" sum:"<<sum<<endl;system("pause");
while(i<j && min>=height[j]){
sum+=min-height[j];
j--;
}
}
else{
max=height[j];min=height[i];i++;
//cout<<"右大 i:"<<i<<" j:"<<j<<" min:"<<min<<" max:"<<max<<" sum:"<<sum<<endl;system("pause");
while(i<j && min>=height[i]){
sum+=min-height[i];
i++;
}
}
}
return sum;
}
注意:会报越界错误:
while(height[i]<height[i+1]) i++;
while(height[j]<height[j-1]) i--;
测试例子:[5,4,1,2]
所以要改为:
while (i < j && i + 1 < height.size() && height[i] < height[i + 1]) i++;
while (i < j && j - 1 >= 0 && height[j] < height[j - 1]) j--;