leetcode 718( Maximum Length of Repeated Subarray)

1.题目描述:给定两个数组,在两个数组中,返回包含相同元素最多的数组的长度。
例子:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
返回:3.
解释:在数组 A和B中最长的子数组为[3,2,1]长度为3.

2.代码:

class Solution{
    public int findLength(int [] A, int [] B){
    int res = 0;
    // java 中 int 默认值为0,需要前一个的值因此长度要比以前的数组大一
    int [][] dp = new int[A.length+1][B.length+1];
    for(int i = 0; i < A.length; i++){
        for(int j = 0; j < B.length; j++){
        if(A[i] == B[j]){
            dp[i+1][j+1] = dp[i][j] +1;
        }
        res = Math.max(res, dp[i+1][j+1]);
        }
    }
    return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章