题解 | #接雨水问题#
接雨水问题
https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * max water * @param arr int整型一维数组 the array * @return long长整型 */ public long maxWater (int[] arr) { // write code here int maxIndex = 0; // 先找到中间那根最粗的 for (int i = 1; i < arr.length; i++) { if (arr[i] > arr[maxIndex]) { maxIndex = i; } } int left = arr[0]; int right = arr[arr.length - 1]; int i = 0; int j = arr.length - 1; int sum = 0; while (i <= maxIndex && j >= maxIndex && i<j) { // 左边往中间靠拢,遇到比自己小的计算,比自己大的,把自己替换了 while (arr[i] <= left && i < maxIndex) { sum += left - arr[i]; i++; } left = arr[i]; // 右边往中间靠拢,同上 while (arr[j] <= right && j > maxIndex) { sum += right - arr[j]; j--; } right = arr[j]; } return sum; } }