Fork me on GitHub

中等-718-最长重复子数组

LeetCode718

给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。

 输入:

A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出:3
解释:
长度最长的公共子数组是 [3, 2, 1] 。


 提示:

1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100

 

一、暴力超时

class Solution {
    public int findLength(int[] A, int[] B) {
        int res = 0;
        for(int i=0; i<A.length; i++){
            for(int j=0; j<B.length; j++){
                int k = 0;
                while(i+k<A.length && j+k<B.length && A[i+k]==B[j+k]){
                    k++;
                }
                res = Math.max(res,k);
            }
        }
        return res;
    }
}

 

 

二、滑动窗口

在寻找两个子数组时,暴力法需要 A.length * B.length ,而滑动窗口仅需 A.length+B.length 。

class Solution {
    public int findLength(int[] A, int[] B) {
        int n = A.length, m = B.length;
        int res = 0;
        // A固定 B向右滑动
        for (int i = 0; i < n; i++) {
            int len = Math.min(m, n - i);
            int maxlen = maxLength(A, B, i, 0, len);
            res = Math.max(res, maxlen);
        }
        // A固定 B向左滑动
        for (int i = 0; i < m; i++) {
            int len = Math.min(n, m - i);
            int maxlen = maxLength(A, B, 0, i, len);
            res = Math.max(res, maxlen);
        }
        return res;
    }
    // aStart与bStart对齐
    public int maxLength(int[] A, int[] B, int aStart, int bStart, int len){
        int res = 0, cur = 0;
        for(int i=0; i<len; i++){
            if(A[aStart+i]==B[bStart+i])
                res = Math.max(res,++cur);
            else cur = 0;
        }
        return res;
    }
}

 

 

三、动态规划(待补充)

 

posted @ 2020-07-31 10:13  Faded828x  阅读(140)  评论(0编辑  收藏  举报