LeetCode 面试题17.2. 直方图水量
原题链接
困难
作者:
大明湖的鱼
,
2021-04-03 10:36:31
,
所有人可见
,
阅读 311
方法一:按层遍历
class Solution {
public:
int trap(vector<int>& height) {
int Sum = accumulate(height.begin(),height.end(),0);
int volume = 0;
int layer = 1;
int n = height.size();
int left = 0 ;
int right = n-1;
while(left <= right){
while(left <= right && height[left] < layer)
left++;
while(left <= right && height[right] < layer)
right--;
volume += right-left+1;
layer++;
}
return volume - Sum;
}
};
方法二:正序遍历一次记录左边最大值,逆序遍历一次记录每个元素的右边最大值,每个位置的存水量就是min(left_max,right_max)- 该点的height;