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: