题目
https://leetcode-cn.com/problems/trapping-rain-water/
思路-双指针
双指针往中间走,并分别维持左右走过的最大值,遇到较小值说明踩到了水。
class Solution {public int trap(int[] height) {int res = 0;int l = 0;int r = height.length - 1;int maxL = 0; // [0..l]之间遇到的最高的柱子int maxR = 0; // [n-1..r]之间遇到的最高的柱子while (l < r) {if (height[l] < height[r]) {if (height[l] < maxL) { // 踩水坑里了,计算水坑面积res += maxL - height[l];} else { // 遇到更高的柱子,更新maxLmaxL = height[l];}l++;} else {if (height[r] < maxR) { // 踩水坑里了,计算水坑面积res += maxR - height[r];} else {maxR = height[r];}r--;}}return res;}}
