Merge pull request #2461 from YangZhaoo/review

接雨水 Java 双指针优化
This commit is contained in:
程序员Carl
2024-04-06 11:47:24 +08:00
committed by GitHub

View File

@ -440,6 +440,33 @@ class Solution {
}
```
双指针优化
```java
class Solution {
public int trap(int[] height) {
if (height.length <= 2) {
return 0;
}
// 从两边向中间寻找最值
int maxLeft = height[0], maxRight = height[height.length - 1];
int l = 1, r = height.length - 2;
int res = 0;
while (l <= r) {
// 不确定上一轮是左边移动还是右边移动,所以两边都需更新最值
maxLeft = Math.max(maxLeft, height[l]);
maxRight = Math.max(maxRight, height[r]);
// 最值较小的一边所能装的水量已定,所以移动较小的一边。
if (maxLeft < maxRight) {
res += maxLeft - height[l ++];
} else {
res += maxRight - height[r --];
}
}
return res;
}
}
```
单调栈法
```java