提交 3d72935d 编写于 作者: E eric496 提交者: labuladong

添加接雨水Java+Python代码

上级 4a504699
......@@ -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)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册