Given two integer arrays
nums1
and nums2
, return the maximum length of a subarray that appears in both arrays.Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
Output: 5
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 100
题目大意:
两数组的最长相等子数组
解题思路:
由于是两数组匹配,所以是匹配性DP
dp[i][j]为以nums1[i-1], nums2[j-1]为结尾的最长重复数组,答案为滚动最大值1
2dp[i][j] = dp[i-1][j-1] + 1 if nums1[i-1] == nums2[j-1]
= 0 if nums1[i-1] != nums2[j-1]
类似题目:
LeetCode 1143 Longest Common Subsequence, 求最长公共子字符串
Karat 002 Longest Common Continuous Subarray 一样的题目,结果类型不同:最长长度和结果
解题步骤:
N/A
注意事项:
Python代码:
1 | # dp[i][j] = dp[i-1][j-1] + 1 if nums1[i-1] == nums2[j-1] |
算法分析:
时间复杂度为O(n2)
,空间复杂度O(n2)