Skip to content

Commit 219d1d9

Browse files
committed
改进718.最长重复子数组Java版本代码
1 parent 20ec965 commit 219d1d9

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

problems/0718.最长重复子数组.md

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ B: [3,2,1,4,7]
2020
输出:3
2121
解释:
2222
长度最长的公共子数组是 [3, 2, 1]
23-
 
23+
2424
提示:
2525

2626
* 1 <= len(A), len(B) <= 1000
@@ -155,6 +155,7 @@ public:
155155

156156
Java:
157157
```java
158+
// 版本一
158159
class Solution {
159160
public int findLength(int[] nums1, int[] nums2) {
160161
int result = 0;
@@ -164,14 +165,34 @@ class Solution {
164165
for (int j = 1; j < nums2.length + 1; j++) {
165166
if (nums1[i - 1] == nums2[j - 1]) {
166167
dp[i][j] = dp[i - 1][j - 1] + 1;
167-
max = Math.max(max, dp[i][j]);
168+
result = Math.max(result, dp[i][j]);
168169
}
169170
}
170171
}
171172

172173
return result;
173174
}
174175
}
176+
177+
// 版本二: 滚动数组
178+
class Solution {
179+
public int findLength(int[] nums1, int[] nums2) {
180+
int[] dp = new int[nums2.length + 1];
181+
int result = 0;
182+
183+
for (int i = 1; i <= nums1.length; i++) {
184+
for (int j = nums2.length; j > 0; j--) {
185+
if (nums1[i - 1] == nums2[j - 1]) {
186+
dp[j] = dp[j - 1] + 1;
187+
} else {
188+
dp[j] = 0;
189+
}
190+
result = Math.max(result, dp[j]);
191+
}
192+
}
193+
return result;
194+
}
195+
}
175196
```
176197

177198
Python:

0 commit comments

Comments
 (0)