mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
改进718.最长重复子数组Java版本代码
This commit is contained in:
@ -20,7 +20,7 @@ B: [3,2,1,4,7]
|
|||||||
输出:3
|
输出:3
|
||||||
解释:
|
解释:
|
||||||
长度最长的公共子数组是 [3, 2, 1] 。
|
长度最长的公共子数组是 [3, 2, 1] 。
|
||||||
|
|
||||||
提示:
|
提示:
|
||||||
|
|
||||||
* 1 <= len(A), len(B) <= 1000
|
* 1 <= len(A), len(B) <= 1000
|
||||||
@ -155,6 +155,7 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
```java
|
||||||
|
// 版本一
|
||||||
class Solution {
|
class Solution {
|
||||||
public int findLength(int[] nums1, int[] nums2) {
|
public int findLength(int[] nums1, int[] nums2) {
|
||||||
int result = 0;
|
int result = 0;
|
||||||
@ -164,7 +165,7 @@ class Solution {
|
|||||||
for (int j = 1; j < nums2.length + 1; j++) {
|
for (int j = 1; j < nums2.length + 1; j++) {
|
||||||
if (nums1[i - 1] == nums2[j - 1]) {
|
if (nums1[i - 1] == nums2[j - 1]) {
|
||||||
dp[i][j] = dp[i - 1][j - 1] + 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;
|
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:
|
Python:
|
||||||
|
Reference in New Issue
Block a user