改进718.最长重复子数组Java版本代码

This commit is contained in:
hk27xing
2021-07-10 21:09:42 +08:00
parent 20ec9659bb
commit 219d1d9982

View File

@ -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