mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -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
|
||||
|
Reference in New Issue
Block a user