LeetCode 题解工作台
图像重叠
给你两个图像 img1 和 img2 ,两个图像的大小都是 n x n ,用大小相同的二进制正方形矩阵表示。二进制矩阵仅由若干 0 和若干 1 组成。 转换 其中一个图像,将所有的 1 向左,右,上,或下滑动任何数量的单位;然后把它放在另一个图像的上面。该转换的 重叠 是指两个图像 都 具有 1 的…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·matrix
答案摘要
我们可以枚举 和 的每个 的位置,分别记为 $(i, j)$ 和 $(h, k)$。然后我们计算得到偏移量 $(i - h, j - k)$,记为 $(dx, dy)$,用哈希表 记录每个偏移量出现的次数。最后我们遍历哈希表 ,找到出现次数最多的偏移量,即为答案。 时间复杂度 ,空间复杂度 。其中 是 的边长。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你两个图像 img1 和 img2 ,两个图像的大小都是 n x n ,用大小相同的二进制正方形矩阵表示。二进制矩阵仅由若干 0 和若干 1 组成。
转换 其中一个图像,将所有的 1 向左,右,上,或下滑动任何数量的单位;然后把它放在另一个图像的上面。该转换的 重叠 是指两个图像 都 具有 1 的位置的数目。
请注意,转换 不包括 向任何方向旋转。越过矩阵边界的 1 都将被清除。
最大可能的重叠数量是多少?
示例 1:
输入:img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]] 输出:3 解释:将 img1 向右移动 1 个单位,再向下移动 1 个单位。两个图像都具有
1的位置的数目是 3(用红色标识)。![]()
示例 2:
输入:img1 = [[1]], img2 = [[1]] 输出:1
示例 3:
输入:img1 = [[0]], img2 = [[0]] 输出:0
提示:
n == img1.length == img1[i].lengthn == img2.length == img2[i].length1 <= n <= 30img1[i][j]为0或1img2[i][j]为0或1
解题思路
方法一:枚举
我们可以枚举 和 的每个 的位置,分别记为 和 。然后我们计算得到偏移量 ,记为 ,用哈希表 记录每个偏移量出现的次数。最后我们遍历哈希表 ,找到出现次数最多的偏移量,即为答案。
时间复杂度 ,空间复杂度 。其中 是 的边长。
class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
cnt = Counter()
for i in range(n):
for j in range(n):
if img1[i][j]:
for h in range(n):
for k in range(n):
if img2[h][k]:
cnt[(i - h, j - k)] += 1
return max(cnt.values()) if cnt else 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to recognize and optimize brute force solutions.
- question_mark
Experience with sliding window or hashing techniques for optimization.
- question_mark
Understanding of matrix manipulation and translation operations.
常见陷阱
外企场景- error
Failing to account for translations outside the matrix boundaries.
- error
Overlooking the need to optimize the brute force approach for larger matrices.
- error
Misunderstanding the problem as one requiring rotation, when only translation is allowed.
进阶变体
外企场景- arrow_right_alt
Handling larger matrices where brute force is inefficient.
- arrow_right_alt
Including additional constraints such as specific translations or partial overlaps.
- arrow_right_alt
Adapting the problem for non-square matrices or non-binary values.
两个图像都具有