1. 程式人生 > >LC 718. Maximum Length of Repeated Subarray

LC 718. Maximum Length of Repeated Subarray

 

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. 1 <= len(A), len(B) <= 1000
  2. 0 <= A[i], B[i] < 100

 

Runtime: 78 ms, faster than 40.98% of Java online submissions for Maximum Length of Repeated Subarray.

 

class Solution {
  public int findLength(int[] A, int[] B) {
    int[][] dp = new int[A.length+1][B.length+1];
    int
ret = 0; for(int i=1; i<dp.length; i++){ for(int j=1; j<dp[0].length; j++){ if(A[i-1] == B[j-1]){ dp[i][j] = dp[i-1][j-1] + 1; ret = Math.max(ret, dp[i][j]); } } } return ret; } }

 

a better solution

Runtime: 26 ms, faster than 99.59% of Java online submissions for Maximum Length of Repeated Subarray.

 

有兩個關鍵點,

第一個是內層迴圈從後往前遍歷,如果從前往後遍歷就是錯誤的,因為我們每一次更新dp的時候是dp[j+1] = dp[j] + 1,所以在更新j+1的時候要用到j的資訊,而這個j應該是之前的j,也就是上一行的j,可以參考上面一個解法中矩陣的上一行。

第二個是如果沒有匹配到,應該把j+1變成0,否則會產生錯誤的計數。

 

class Solution {
    public int findLength(int[] A, int[] B) {
        int[] dp = new int[A.length+1];
        int max = 0;
        for(int i=0; i<A.length; i++) {
            for(int j=B.length-1; j>=0; j--) {
                if (A[i] == B[j]) {
                    dp[j+1] = dp[j] + 1;
                    if (max < dp[j+1]) {
                        max = dp[j+1];
                    }
                } else {
                    dp[j+1] = 0;
                }
            }
        }
        return max;
    }  
}