718. Maximum Length of Repeated Subarray
- 题目
- 代码块
- 想法
Description
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].
代码
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int res[A.size()][B.size()];
int maxnum = 0;
for(int i = 0 ; i < A.size(); i++){
if(A[i] != B[0]){
res[i][0] = 0;
}
else{
res[i][0] = 1;
}
}
for(int j = 0 ; j < A.size(); j++){
if(A[0] != B[j]){
res[0][j] = 0;
}
else{
res[0][j] = 1;
}
}
for(int i = 1; i < A.size(); i++){
for(int j = 1; j < A.size(); j++){
if(A[i] != B[j]){
res[i][j] = 0;
}
else{
res[i][j] = res[i-1][j-1] + 1;
if(res[i][j] > maxnum){
maxnum = res[i][j];
}
}
}
}
return maxnum;
}
};
int main(){
int A[] = {3,2,1,4,7};
int B[] = {1,2,3,2,1};
vector<int> arr1(A,A+5);
vector<int> arr2(B,B+5);
Solution S;
cout<<S.findLength(arr1,arr2);
}
想法
要计算最大公共子数组长度,设res[i][j]为A前i个和B前j个的最大子数组长度,后来想想,因为res[i][j]只与res[i-1][j-1]有关系,和其他没有关系,所以先赋值第一行第一列为相应的0和1,然后从i=1开始,不断计算倾斜边,即可求到最大值.