From 219d1d9982bd57dd1249abc1c08f049215104ca1 Mon Sep 17 00:00:00 2001 From: hk27xing <244798299@qq.com> Date: Sat, 10 Jul 2021 21:09:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9B718.=E6=9C=80=E9=95=BF?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E5=AD=90=E6=95=B0=E7=BB=84Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0718.最长重复子数组.md | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/problems/0718.最长重复子数组.md b/problems/0718.最长重复子数组.md index bef616d3..9ee94a3d 100644 --- a/problems/0718.最长重复子数组.md +++ b/problems/0718.最长重复子数组.md @@ -20,7 +20,7 @@ B: [3,2,1,4,7] 输出:3 解释: 长度最长的公共子数组是 [3, 2, 1] 。 -  + 提示: * 1 <= len(A), len(B) <= 1000 @@ -155,6 +155,7 @@ public: Java: ```java +// 版本一 class Solution { public int findLength(int[] nums1, int[] nums2) { int result = 0; @@ -164,7 +165,7 @@ class Solution { for (int j = 1; j < nums2.length + 1; j++) { if (nums1[i - 1] == nums2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; - max = Math.max(max, dp[i][j]); + result = Math.max(result, dp[i][j]); } } } @@ -172,6 +173,26 @@ class Solution { return result; } } + +// 版本二: 滚动数组 +class Solution { + public int findLength(int[] nums1, int[] nums2) { + int[] dp = new int[nums2.length + 1]; + int result = 0; + + for (int i = 1; i <= nums1.length; i++) { + for (int j = nums2.length; j > 0; j--) { + if (nums1[i - 1] == nums2[j - 1]) { + dp[j] = dp[j - 1] + 1; + } else { + dp[j] = 0; + } + result = Math.max(result, dp[j]); + } + } + return result; + } +} ``` Python: