LeetCode 题解工作台

最长重复子数组

给两个整数数组 nums1 和 nums2 ,返回 两个数组中 公共的 、长度最长的子数组的长度 。 示例 1: 输入: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] 输出: 3 解释: 长度最长的公共子数组是 [3,2,1] 。 示例 2: 输入: nums1 …

category

6

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示以 $nums1[i - 1]$ 和 $nums2[j - 1]$ 结尾的最长公共子数组的长度,那么我们可以得到状态转移方程: $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

提示:

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

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 表示以 nums1[i1]nums1[i - 1]nums2[j1]nums2[j - 1] 结尾的最长公共子数组的长度,那么我们可以得到状态转移方程:

f[i][j]={0,nums1[i1]nums2[j1]f[i1][j1]+1,nums1[i1]=nums2[j1]f[i][j]= \begin{cases} 0, & nums1[i - 1] \neq nums2[j - 1] \\ f[i - 1][j - 1] + 1, & nums1[i - 1] = nums2[j - 1] \end{cases}

最终的答案即为所有 f[i][j]f[i][j] 中的最大值。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别是数组 nums1nums1nums2nums2 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def findLength(self, nums1: List[int], nums2: List[int]) -> int:
        m, n = len(nums1), len(nums2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        ans = 0
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if nums1[i - 1] == nums2[j - 1]:
                    f[i][j] = f[i - 1][j - 1] + 1
                    ans = max(ans, f[i][j])
        return ans
speed

复杂度分析

指标
时间O((M+N) * \log{(\min(M, N))})
空间O(M)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an understanding of state transition dynamic programming.

  • question_mark

    The candidate should propose optimizations such as binary search or rolling hash.

  • question_mark

    Pay attention to how well they can balance time and space complexity in their approach.

warning

常见陷阱

外企场景
  • error

    Incorrectly handling indices while accessing elements in the dp table.

  • error

    Over-complicating the solution when a simple dynamic programming approach suffices.

  • error

    Failing to optimize for space when the problem constraints are large.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the arrays are very large (greater than 1000 elements)?

  • arrow_right_alt

    Can this problem be solved in linear time?

  • arrow_right_alt

    What if the arrays contain non-integer values or negative numbers?

help

常见问题

外企场景

最长重复子数组题解:状态·转移·动态规划 | LeetCode #718 中等