您的位置:首页 > 其它

Maximum Length of Repeated Subarray

2018-01-17 00:00 274 查看
问题:

Given two integer arrays
A
and
B
, return the maximum length of an subarray that appears in both arrays.

Example 1:

Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].

Note:

1 <= len(A), len(B) <= 1000

0 <= A[i], B[i] < 100

解决:

① 给定两个数组A和B,返回两个数组的最长重复子数组。

dp[i][j]表示数组A的前i个数字和数组B的前j个数字的最长重复子数组的长度,如果dp[i][j]不为0,则A中第i个数组和B中第j个数字必须相等。

以[1,2,2]和[3,1,2]为例,dp数组为:

3 1 2
1 0 1 0
2 0 0 2
2 0 0 1

当A[i] == B[j]时,dp[i][j] = dp[i - 1][j - 1] + 1;

当A[i] != B[j]时,dp[i][j] = 0;

每次算出一个dp值,都要用来更新结果res,这样就能得到最长相同子数组的长度了。

class Solution { //83ms
public int findLength(int[] A, int[] B) {
int res = 0;
int[][] dp = new int[A.length + 1][B.length + 1];
for (int i = 1;i < dp.length;i ++){
for (int j = 1;j < dp[i].length;j ++){
dp[i][j] = (A[i - 1] == B[j - 1]) ? dp[i - 1][j - 1] + 1 : 0;
res = Math.max(res,dp[i][j]);
}
}
return res;
}
}

② 简化为一维数组。

class Solution { //41ms
public int findLength(int[] A, int[] B) {
int res = 0;
int[] dp = new int[B.length + 1];
for (int i = 1;i <= A.length;i ++){
for (int j = B.length;j > 0;j --){
if (A[i - 1] == B[j - 1]){
dp[j] = dp[j - 1] + 1;
res = Math.max(res,dp[j]);
}else {
dp[j] = 0;
}
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: