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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章