From 3d72935db12675b54e506c2d0e08de02193ca569 Mon Sep 17 00:00:00 2001 From: eric496 Date: Sun, 21 Jun 2020 23:09:43 -0400 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=8E=A5=E9=9B=A8=E6=B0=B4Ja?= =?UTF-8?q?va+Python=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../\346\216\245\351\233\250\346\260\264.md" | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\216\245\351\233\250\346\260\264.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\216\245\351\233\250\346\260\264.md" index 6718ddb8ac..b5f20ff132 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\216\245\351\233\250\346\260\264.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\346\216\245\351\233\250\346\260\264.md" @@ -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)