题目
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例 1:
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
示例 2:
输入:height = [4,2,0,3,2,5]
输出:9
提示:
n == height.length
0 <= n <= 3 * 104
0 <= height[i] <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trapping-rain-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
从图可以看出来,当前下标的高度取决于左右高度中最矮的,比如坐标3的高度为Math.min(nums[i-1]-nums[i], nums[i+1]-nums[i])=Math.min(1-0, 2-0),其实就是木桶原理。
而从全局看,如果当前下标左边有比相邻边更高的,应该是左边最高的那个边与当前的差。比如,如图:下标5高度为0,下标4高度为1,下标3高度为2,下标6高度为1,下标7高度为3。下标5的积水高度为Math.min(Math.max(left0, left1, …), Math.max(right0, right1, …)) = Math.min(Math.max(2, 1) - 0, Math.max(1,3) - 0) = Math.min(2, 3) = 2。
所以定义两个变量左右的最大值,leftMax,rightMax。
答案
class Solution {
public int trap(int[] height) {
if (height.length == 0) {
return 0;
}
int left = 0;
int right = height.length - 1;
int result = 0;
// 左右最大值
int leftMax = height[left];
int rightMax = height[right];
while (left < right) {
int leftH = height[left];
int rightH = height[right];
if (leftH < rightH) {
if (leftH > leftMax) {
// 此时,不会积水,因为当前的高于左边的。
// 为什么不判断右边,是因为左边的最大值小于右边
leftMax = leftH;
} else {
result += leftMax - leftH;
}
left++;
} else {
if (rightH > rightMax) {
// 同上
rightMax = rightH;
} else {
result += rightMax - rightH;
}
right--;
}
}
return result;
}
}