您好,欢迎访问一九零五行业门户网

LeetCode 最长重复子数组 Maximum Length of Repeated Subarray

本文介绍了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
python 用list of lists表示矩阵的问题?
以上就是leetcode 最长重复子数组 maximum length of repeated subarray的详细内容。
其它类似信息

推荐信息