本文介绍了leetcode 最长重复子数组 maximum length of repeated subarray,希望大家耐心学习。
给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。
示例 1:
输入:A: [1,2,3,2,1] B: [3,2,1,4,7]输出: 3解释: 长度最长的公共子数组是 [3, 2, 1]。
说明:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 10
解法,这是一道经典的动态规划算法,如下:
public class MaxLengthRepeatedSubarray {
//动态规划算法
public static int findLength(int[] A, int[] B) {
int aSize = A.length;
int bSize = B.length;
int[][] dp = new int[aSize + 1][bSize + 1];
int result = 0;
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[i].length; j++) {
dp[i][j] = A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : 0;
result = Math.max(result, dp[i][j]);
}
}
return result;
}
public static void main(String[] args) {
int[] a = new int[]{1, 2, 3, 2, 1};
int[] b = new int[]{3, 2, 1, 4, 7};
System.out.println(findLength(a, b));
}
}相关推荐:
LeetCode 2 Evaluate Reverse Polish Notation
以上就是LeetCode 最长重复子数组 Maximum Length of Repeated Subarray的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号