思路:
最后无论原图形如何都会形成阶梯型,而每个阶梯型与力扣11.最大盛水容器类似,所以本题选择双指针法,首先查找到最高的一节,然后中心扩散。
第一步,找到最高点,left指针与right指针同时指向该点
第二步,双指针向左右扩散,找到次高点,计算与left,right之间的容量
第三步,继续向左向右找次高点,计算盛水面积
第四步继续进行扩散
结束,返回总面积。
package oneProject;
public class Trap {
public int trap(int[] height) {
all = 0;
return getV(height,0,height.length - 1);
}
int all = 0;
public int getV(int[] height,int start,int end) {
int highest = getMaxIndex(height,start,end);
int leftMax = highest;
int rightMax = highest;
while(leftMax != start || rightMax != end) {
int left = start;
if(leftMax != start) {
//向左找最次高的;
left = getMaxIndex(height,start,leftMax - 1);
//从左向右次高的向中间遍历
for(int i = left;i < leftMax;i++) {
all += height[left] - height[i];
}
}
int right = end;
if(rightMax != end) {
//向右找最次高的;
right = getMaxIndex(height,rightMax + 1,end);
//从右向左次高的向中间遍历
for(int i = right; i > rightMax; i--) {
all += height[right] - height[i];
}
}
//更新最左最右
leftMax = left;
rightMax = right;
}
return all;
}
public int getMaxIndex(int[] height,int start,int end) {
int max = start;
for(int i = start; i <= end; i++) {
if(height[i] > height[max]) {
max = i;
}
}
return max;
}
}