From 6aa102ed744836d2053da3e5bb13c0f1c5b56482 Mon Sep 17 00:00:00 2001 From: ironartisan Date: Sun, 15 Aug 2021 22:26:57 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A00042.=E6=8E=A5=E9=9B=A8?= =?UTF-8?q?=E6=B0=B4java=E5=8F=8C=E6=8C=87=E9=92=88=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0042.接雨水.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index 235776a0..b3ee84fd 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -365,7 +365,31 @@ public: ## 其他语言版本 Java: +双指针法 +```java +class Solution { + public int trap(int[] height) { + int sum = 0; + for (int i = 0; i < height.length; i++) { + // 第一个柱子和最后一个柱子不接雨水 + if (i==0 || i== height.length - 1) continue; + + int rHeight = height[i]; // 记录右边柱子的最高高度 + int lHeight = height[i]; // 记录左边柱子的最高高度 + for (int r = i+1; r < height.length; r++) { + if (height[r] > rHeight) rHeight = height[r]; + } + for (int l = i-1; l >= 0; l--) { + if(height[l] > lHeight) lHeight = height[l]; + } + int h = Math.min(lHeight, rHeight) - height[i]; + if (h > 0) sum += h; + } + return sum; + } +} +``` Python: 双指针法 From 2405f03d94320d195c97e9719853297d5373aeaf Mon Sep 17 00:00:00 2001 From: ironartisan Date: Tue, 17 Aug 2021 11:21:23 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A00042.=E6=8E=A5=E9=9B=A8?= =?UTF-8?q?=E6=B0=B4java=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0042.接雨水.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0042.接雨水.md b/problems/0042.接雨水.md index c241b441..22c8c0ef 100644 --- a/problems/0042.接雨水.md +++ b/problems/0042.接雨水.md @@ -365,6 +365,7 @@ public: ## 其他语言版本 Java: + 双指针法 ```java class Solution { @@ -390,6 +391,33 @@ class Solution { } } ``` +动态规划法 +```java +class Solution { + public int trap(int[] height) { + int length = height.length; + if (length <= 2) return 0; + int[] maxLeft = new int[length]; + int[] maxRight = new int[length]; + + // 记录每个柱子左边柱子最大高度 + maxLeft[0] = height[0]; + for (int i = 1; i< length; i++) maxLeft[i] = Math.max(height[i], maxLeft[i-1]); + + // 记录每个柱子右边柱子最大高度 + maxRight[length - 1] = height[length - 1]; + for(int i = length - 2; i >= 0; i--) maxRight[i] = Math.max(height[i], maxRight[i+1]); + + // 求和 + int sum = 0; + for (int i = 0; i < length; i++) { + int count = Math.min(maxLeft[i], maxRight[i]) - height[i]; + if (count > 0) sum += count; + } + return sum; + } +} +``` Python: 双指针法