0
点赞
收藏
分享

微信扫一扫

LeetCode 718.最长重复子数组

1.题目:

给两个整数数组 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



2.代码:

class Solution {
    public int findLength(int[] nums1, int[] nums2) {
       int[][] dp = new int[nums1.length][nums2.length];
       int max=Integer.MIN_VALUE;
       for(int i=0;i<nums1.length;i++){
           for(int j=0;j<nums2.length;j++){
               if(nums1[i]==nums2[j]){
                   if(i==0 || j==0){
                       dp[i][j]=1;
                   }else{
                        dp[i][j]=dp[i-1][j-1]+1;
                   }
                 
               }else{
                   dp[i][j]=0;
               }
                max=Math.max(max,dp[i][j]);
           }
          
       }
       return max;
    }
}



class Solution {
    public int findLength(int[] nums1, int[] nums2) {
        int result = 0;
        int[][] dp = new int[nums1.length + 1][nums2.length + 1];
        
        for (int i = 1; i < nums1.length + 1; i++) {
            for (int j = 1; j < nums2.length + 1; j++) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    result = Math.max(result, dp[i][j]);
                }
            }
        }
        
        return result;
    }
}


LeetCode 718.最长重复子数组_Math





举报

相关推荐

0 条评论