leetcode718. 最长重复子数组

该博客介绍了一个算法问题,目标是找到两个整数数组的最长公共子数组,并给出了一个解决方案。算法使用动态规划(动态规划表dp)来计算最长公共子数组的长度,最终返回最大长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

地址https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/
描述
  给两个整数数组 nums1 和 nums2 ,返回两个数组中公共的 、长度最长的子数组的长度 。
实例1

输入:nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
输出:3
解释:长度最长的公共子数组是 [3,2,1] 。

实例2

输入:nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
输出:5

思路

答案

class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int length1 = nums1.length;
        int length2 = nums2.length;

        int[][] dp = new int[length1 + 1][length2 + 2];

        int res = 0;
        for (int i = 1; i <= length1; i++) {
            for (int j = 1; j <= length2; j++) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    res = Math.max(res, dp[i][j]);
                }
            }
        }

        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值