题目
具体代码
class Solution {
public int trap(int[] height) {
if(height == null || height.length == 0){
return 0;
}
//遍历数组,找出最高的高度以及对应的下标
int max = 0,max_index = 0;
for(int i = 0;i < height.length;i++){
if(height[i]>max){
max = height[i];
max_index = i;
}
}
//从左往右遍历到最高高度索引处
int left = height[0];
int sum = 0;
for(int i = 1;i < max_index;i++){
if(height[i]>=left){
left = height[i];
}else{
sum += left - height[i];
}
}
left = 0;
for(int i = height.length-1;i > max_index;i--){
if(height[i]>=left){
left = height[i];
}else{
sum += left - height[i];
}
}
return sum;
}
}
参考资料
https://leetcode-cn.com/problems/volume-of-histogram-lcci/solution/1msshuang-100-by-wei-yu-13-2/