接雨水问题
问题链接 https://leetcode-cn.com/problems/trapping-rain-water/
public static int trap(int[] height) {
int s =0;
int heig = 0;
//当前水位
for(int i=0;i<height.length;i++){
if(height[i]<1&&heig==0){ continue;}
int leftIndex = i;
int thisHeigh = getHeig(height,i,heig);
heig = thisHeigh;
if(thisHeigh == 0){
break;
}
//如果高于水位
if(height[leftIndex]>=thisHeigh){
continue;
}
//如果低于shuiwei
int add =thisHeigh-height[leftIndex];
s+=add;
}
return s;
}
public static int min(int a,int b){
return a<b? a:b;
}
public static int getHeig(int height[],int leftIndex,int heig){
int leftHeight = height[leftIndex];
int max = getMax(height,leftIndex+1);
if(max<heig){ //如果后面盛不了这么多水了,则降低水位
return max;
}
int min = min(leftHeight,max); //获取最低的挡板
return min<heig?heig:min; //如果挡板比水位低,且后面能盛那么多水,则继续盛水位的水
}
public static int getMax(int height[],int leftIndex){
if(leftIndex>height.length-1){
return 0;
}
int max = height[leftIndex];
for(int i=leftIndex+1;i<height.length;i++){
if(max < height[i]){
max = height[i];
}
}
return max;
}