LeetCode 题解工作台

图像重叠

给你两个图像 img1 和 img2 ,两个图像的大小都是 n x n ,用大小相同的二进制正方形矩阵表示。二进制矩阵仅由若干 0 和若干 1 组成。 转换 其中一个图像,将所有的 1 向左,右,上,或下滑动任何数量的单位;然后把它放在另一个图像的上面。该转换的 重叠 是指两个图像 都 具有 1 的…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·matrix

bolt

答案摘要

我们可以枚举 和 的每个 的位置,分别记为 $(i, j)$ 和 $(h, k)$。然后我们计算得到偏移量 $(i - h, j - k)$,记为 $(dx, dy)$,用哈希表 记录每个偏移量出现的次数。最后我们遍历哈希表 ,找到出现次数最多的偏移量,即为答案。 时间复杂度 ,空间复杂度 。其中 是 的边长。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个图像 img1img2 ,两个图像的大小都是 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].length
  • n == img2.length == img2[i].length
  • 1 <= n <= 30
  • img1[i][j]01
  • img2[i][j]01
lightbulb

解题思路

方法一:枚举

我们可以枚举 img1\textit{img1}img2\textit{img2} 的每个 11 的位置,分别记为 (i,j)(i, j)(h,k)(h, k)。然后我们计算得到偏移量 (ih,jk)(i - h, j - k),记为 (dx,dy)(dx, dy),用哈希表 cnt\textit{cnt} 记录每个偏移量出现的次数。最后我们遍历哈希表 cnt\textit{cnt},找到出现次数最多的偏移量,即为答案。

时间复杂度 O(n4)O(n^4),空间复杂度 O(n2)O(n^2)。其中 nnimg1\textit{img1} 的边长。

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

图像重叠题解:数组·matrix | LeetCode #835 中等