Skip to content

Commit

Permalink
提交接雨水java解法
Browse files Browse the repository at this point in the history
  • Loading branch information
kptnewler authored and labuladong committed Jun 24, 2020
1 parent 5f02952 commit 5967110
Showing 1 changed file with 83 additions and 1 deletion.
84 changes: 83 additions & 1 deletion 高频面试系列/接雨水.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,88 @@ if (l_max < r_max) {

![labuladong](../pictures/labuladong.jpg)

暴力解法

```java
public int trap(int[] height) {
int ans = 0;
for (int i = 1; i < height.length - 1; i++) {
int leftMax = 0, rightMax = 0;
// 找右边最高的柱子
for (int j = i; j < height.length; j++) {
rightMax = Math.max(height[j], rightMax);
}
// 找左边最高的柱子
for (int j = i; j >= 0; j--) {
leftMax = Math.max(height[j], leftMax);
}
// 如果自己就是最高的话,
// leftMax == rightMax == height[i]
ans += Math.min(leftMax, rightMax) - height[i];
}
return ans;
}
```

备忘录优化解法

```java
public int trap(int[] height) {
if (height == null || height.length == 0) return 0;
int ans = 0;
// 数组充当备忘录
int[] leftMax = new int[height.length];
int[] rightMax = new int[height.length];
// 初始化base case
leftMax[0] = height[0];
rightMax[height.length - 1] = height[height.length - 1];
// 从左到右计算leftMax
for (int i = 1; i < height.length; i++) {
leftMax[i] = Math.max(height[i], leftMax[i-1]);
}
// 从右到左计算rightMax
for (int i = height.length - 2; i >= 0; i--) {
rightMax[i] = Math.max(height[i], rightMax[i + 1]);
}
// 计算结果
for (int i = 1; i < height.length - 1; i++) {
ans += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return ans;
}
```

双指针解法

```java
public int trap(int[] height) {
if (height == null || height.length == 0) return 0;

int ans = 0;
int leftMax, rightMax;
// 左右指针
int left = 0, right = height.length - 1;
// 初始化
leftMax = height[0];
rightMax = height[height.length - 1];

while (left < right) {
// 更新左右两边柱子最大值
leftMax = Math.max(height[left], leftMax);
rightMax = Math.max(height[right], rightMax);

// 相当于ans += Math.min(leftMax, rightMax) - height[i]
if (leftMax < rightMax) {
ans += leftMax - height[left];
left++;
} else {
ans += rightMax - height[right];
right--;
}
}
return ans;
}
```

[eric wang](https://www.github.com/eric496) 提供 Java 代码

Expand Down Expand Up @@ -248,4 +330,4 @@ def trap(self, height: List[int]) -> int:

[下一篇:如何去除有序数组的重复元素](../高频面试系列/如何去除有序数组的重复元素.md)

[目录](../README.md#目录)
[目录](../README.md#目录)

0 comments on commit 5967110

Please sign in to comment.