算法 【双指针】接雨水 求解代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public long maxWater(int[] arr) { // 数组长度<3,无法形成凹坑接水,直接返回0 if (arr == null || arr.length < 3) { return 0; } int left = 0; // 左指针 int right = arr.length - 1; // 右指针 long ans = 0; // 总积水量 int leftMax = arr[left]; // 左指针左侧(含当前)的最大柱子高度,初始为左指针初始值 int rightMax = arr[right]; // 右指针右侧(含当前)的最大柱子高度,初始为右指针初始值 while (left < right) { // 更新左右最大高度→取最大值,记录遍历过的最高柱子 leftMax = Math.max(leftMax, arr[left]); rightMax = Math.max(rightMax, arr[right]); // 当前位置的积水量由较小的最大高度决定,移动该侧指针可逐步统计积水量 if (leftMax < rightMax) { ans += leftMax - arr[left]; left++; } else { ans += rightMax - arr[right]; right--; } } return ans; // 返回总积水量 }