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;
    }  
}

 

posted @ 2019-01-13 20:20  yuxihong  阅读(169)  评论(0编辑  收藏  举报