接雨水java实现
思路:通过两次循环 ,从前往后 和从后往前,找到能盛水的容器,然后减去中间的黑色部分即可
public static int getRainWater(int[] arr){
int sum = 0;
int left = 0;
int right = left +1;
int len = arr.length;
//从左往右
for (;right< len;right++){
if(arr[left] != 0 && arr[left] <= arr[right]){
for (int i = left +1; i < right; i++){
sum += arr[left] - arr[i];
}
left = right;
} else if(arr[left] == 0){
left = right;
}
}
//从右往左
for (left = len -2,right = len -1; left >=0; left--){
if(arr[right] != 0 && arr[left] >= arr[right]){
for (int i = left+1; i < right; i++){
sum += arr[right] - arr[i];
}
right = left;
} else if(arr[right] == 0){
right = left;
}
}
return sum;
}