题目
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
上面是由数组 [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
题解
这种存水得题目都是在考察双指针。
本题读完题目基本就会发现规律,能存水的就是那些中间蓝色的凹进去的部分。问题转化成很多个小的凹下去的部分怎么求解。左右两个指针,一头一尾开始遍历,首先找到自己这一边的局部最高点,只要比最高点小就可以装水。
class Solution {
public int trap(int[] height) {
if (height.length < 3) {
return 0;
}
//两根指针一头一尾向中间进发
int left = 0;
int right = height.length - 1;
int area = 0;
//两个变量存储左右两边的局部最大高度
int leftMax = 0;
int rightMax = 0;
while (left <= right) {
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
//小的那边可以存水
if (leftMax <= rightMax) {
if (leftMax > height[left]) {
area += leftMax - height[left];
}
left++;
} else {
if (rightMax > height[right]) {
area += rightMax - height[right];
}
right--;
}
}
return area;
}
}
每日英文
- incline (v.) to 易于… 易于的词组还有
- be subject to
- be prone to
- be liable to 有义务做某事,倾向于做某事
- be apt to
- -pre -pro -pri 代表向前倾
- liability 义务
- underline (v.)强调
- stress 压力,强调
- emphasize 强调
- in line with 与…一致
- row 行[数组里面经常提到]
- in a row 连续地
- a row of 一排
- a + (n.) + of / (n.)s + of == some/many
- a succession of
- a lot of
- …
- boundary (n.)边界,边界线
- bound (v./n.)跳跃,束缚
- be bound to 注定做某事
- route (n.)路线
- a circular bus ~ 循环的巴士路线
- successor 继任者
- -suc 向下
- -cess 走的词根