[Leetcode学习-java]Maximum Length of Repeated Subarray

问题:

难度:media

说明:

给出两个数组,求出两个数组中相同最长子串长度。

题目连接:https://leetcode.com/problems/maximum-length-of-repeated-subarray/

输入范围:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 100

输入案例:

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

我的代码:

首先要注意是子串,也就是连续的元素组成的序列,这个用个二维数组去做吧,然后想快一点就再将其中一个数组每一个元素重复的索引记录到一个链表里面,然后进行遍历即可。

Java:

class Solution {
    
    public int findLength(int[] nums1, int[] nums2) {
        int max = 0, index = 0, pre = 0;
        int[] begin = new int[101], end = new int[101], next = new int[nums2.length];
        
        for(int i = 0, len = nums2.length; i < len; i ++) { // 想快一点就记录索引
            if(begin[nums2[i]] == 0) {
                begin[nums2[i]] = end[nums2[i]] = i + 1;
            } else {
                next[end[nums2[i]] - 1] = i + 1;
                end[nums2[i]] = i + 1;
            }
        }
        
        int dp[][] = new int[nums1.length][nums2.length];
        
        for(int i = 0, len1 = nums1.length; i < len1; i ++, pre = 0) 
            for(int j = begin[nums1[i]] - 1; j != -1; j = next[j] - 1) {
                dp[i][j] = i - 1 >= 0 && j - 1 >= 0 ? dp[i - 1][j - 1] + 1 : 1;
                max = Math.max(max, dp[i][j]);
            }
            
        return max;
    }
}

C++:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值