求两个数组的最长重复子数组 Maximum Length of Repeated Subarray
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
問(wèn)題:
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:
解決:
① ?給定兩個(gè)數(shù)組A和B,返回兩個(gè)數(shù)組的最長(zhǎng)重復(fù)子數(shù)組。
dp[i][j]表示數(shù)組A的前i個(gè)數(shù)字和數(shù)組B的前j個(gè)數(shù)字的最長(zhǎng)重復(fù)子數(shù)組的長(zhǎng)度,如果dp[i][j]不為0,則A中第i個(gè)數(shù)組和B中第j個(gè)數(shù)字必須相等。
以[1,2,2]和[3,1,2]為例,dp數(shù)組為:
?? 3 1 2
1 0 1 0
2 0 0 2
2 0 0 1
當(dāng)A[i] == B[j]時(shí),dp[i][j] = dp[i - 1][j - 1] + 1;
當(dāng)A[i] != B[j]時(shí),dp[i][j] = 0;
每次算出一個(gè)dp值,都要用來(lái)更新結(jié)果res,這樣就能得到最長(zhǎng)相同子數(shù)組的長(zhǎng)度了。
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;
? ? }
}
② 簡(jiǎn)化為一維數(shù)組。
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;
? ? }
}
轉(zhuǎn)載于:https://my.oschina.net/liyurong/blog/1608199
總結(jié)
以上是生活随笔為你收集整理的求两个数组的最长重复子数组 Maximum Length of Repeated Subarray的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Git远程操作详解【转】
- 下一篇: 第十期 华为拓扑-OSPF配置