Skip to content

Commit

Permalink
添加接雨水Java+Python代码
Browse files Browse the repository at this point in the history
  • Loading branch information
eric496 authored and labuladong committed Jun 22, 2020
1 parent 4a50469 commit 3d72935
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions 高频面试系列/接雨水.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,66 @@ if (l_max < r_max) {
![labuladong](../pictures/labuladong.jpg)


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

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

int n = height.length;
int left = 0, right = n - 1;
int ans = 0;

int l_max = height[0];
int r_max = height[n - 1];

while (left <= right) {
l_max = Math.max(l_max, height[left]);
r_max = Math.max(r_max, height[right]);

if (l_max < r_max) {
ans += l_max - height[left];
left++;
} else {
ans += r_max - height[right];
right--;
}
}

return ans;
}
```

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

```python
def trap(self, height: List[int]) -> int:
if not height:
return 0

n = len(height)
left, right = 0, n - 1
ans = 0

l_max = height[0]
r_max = height[n - 1]

while left <= right:
l_max = max(l_max, height[left])
r_max = max(r_max, height[right])

if l_max < r_max:
ans += l_max - height[left]
left += 1
else:
ans += r_max - height[right]
right -= 1

return ans
```

[上一篇:如何运用二分查找算法](../高频面试系列/koko偷香蕉.md)

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

0 comments on commit 3d72935

Please sign in to comment.