题目描述

题解
// 双指针法
// 可以看看官方解法解法4 https://leetcode-cn.com/problems/trapping-rain-water/solution/jie-yu-shui-by-leetcode/
//
// 定义答案保存位res,定义左右指针left和right,left从头往尾遍历,右指针
// 从尾往头遍历,定义左右的最高位保存位lmax(left)和rmax(right),
// while循环开始双指针遍历,while停止条件为left和right指针相遇,
// 如果指针在height的遍历数有height[left]小于height[right],
// 则处理左指针这边,如果左指针指向元素height[left]大于等于lmax,更新lmax
// 为height[left],如果height[left]小于lmax,将高度差产生的雨水容量
// lmax - height[right]累加给res。之后left右移
//
// 如果指针的遍历数有height[left]大于等于height[right],
// 则处理元素小的right指针这边,如果此时height[right]大于等于rmax,更新rmax
// 为height[right],否则,将高度差产生的雨水容量rmax - height[right]累加给res,
// 之后right左移。如此循环,最后返回res。
//
// 执行用时:1 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.3 MB, 在所有 Java 提交中击败了13.25%的用户
class Solution {
public int trap(int[] height) {
int res = 0
int left = 0
int right = height.length - 1
int lmax = 0, rmax = 0
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= lmax) lmax = height[left]
else res += (lmax - height[left])
left++
}
else { // height[left] >= height[right]
if (height[right] >= rmax) rmax = height[right]
else res += (rmax - height[right])
right--
}
}
return res
}
}