[LeetCode] 718. Maximum Length of Repeated Subarray

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

最长重复子数组。

题目很好懂。这题可以同1143题一起做,几乎一模一样。

既然是找子数组,而且暴力解一看复杂度就比较高,既要扫描两个数组又要找相同的部分,所以思路是尝试用动态规划来解决问题。动态规划的二维数组 dp[i][j] 的含义是以 A[i] 和 B[j] 为结尾的公共子数组的最长长度。

  • 当 A[i] != B[j] 时,dp[i][j] = 0, 因为以A[i]和B[j]结尾的公共子串不存在,因为他们最后一个数字不同
  • 当 A[i] == B[j] 时,dp[i][j] = dp[i-1][j-1] + 1, 因为 A[i] 和 B[j] 相等,以他们为结尾的最长公共子串的长度就是以 A[i-1] 和 B[j-1] 结尾的最长公共子串长度 + 1

时间O(mn)

空间O(mn)

Java实现

 1 class Solution {
 2     public int findLength(int[] A, int[] B) {
 3         int m = A.length;
 4         int n = B.length;
 5         int[][] dp = new int[m + 1][n + 1];
 6         int res = 0;
 7         for (int i = 1; i <= A.length; i++) {
 8             for (int j = 1; j <= B.length; j++) {
 9                 dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : 0;
10                 res = Math.max(res, dp[i][j]);
11             }
12         }
13         return res;
14     }
15 }

 

JavaScript实现

 1 /**
 2  * @param {number[]} A
 3  * @param {number[]} B
 4  * @return {number}
 5  */
 6 var findLength = function (A, B) {
 7     let m = A.length;
 8     let n = B.length;
 9     let dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
10     let res = 0;
11     for (let i = 1; i <= m; i++) {
12         for (let j = 1; j <= n; j++) {
13             dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : 0;
14             res = Math.max(res, dp[i][j]);
15         }
16     }
17     return res;
18 };

 

相关题目

718. Maximum Length of Repeated Subarray

1143. Longest Common Subsequence

LeetCode 题目总结

posted @ 2020-07-01 03:20  CNoodle  阅读(175)  评论(0编辑  收藏  举报