LeetCode 题解工作台
最长重复子数组
给两个整数数组 nums1 和 nums2 ,返回 两个数组中 公共的 、长度最长的子数组的长度 。 示例 1: 输入: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] 输出: 3 解释: 长度最长的公共子数组是 [3,2,1] 。 示例 2: 输入: nums1 …
6
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示以 $nums1[i - 1]$ 和 $nums2[j - 1]$ 结尾的最长公共子数组的长度,那么我们可以得到状态转移方程: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给两个整数数组 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 <= 10000 <= nums1[i], nums2[i] <= 100
解题思路
方法一:动态规划
我们定义 表示以 和 结尾的最长公共子数组的长度,那么我们可以得到状态转移方程:
最终的答案即为所有 中的最大值。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 和 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O((M+N) * \log{(\min(M, N))}) |
| 空间 | O(M) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?