LeetCode 题解工作台
找出叠涂元素
给你一个下标从 0 开始的整数数组 arr 和一个 m x n 的整数 矩阵 mat 。 arr 和 mat 都包含范围 [1,m * n] 内的 所有 整数。 从下标 0 开始遍历 arr 中的每个下标 i ,并将包含整数 arr[i] 的 mat 单元格涂色。 请你找出 arr 中第一个使得 m…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 记录每个元素在矩阵 中的位置,即 $idx[mat[i][j]] = (i, j)$,定义两个数组 和 分别记录每行和每列已经涂色的元素个数。 遍历数组 ,对于每个元素 ,我们找到其在矩阵 中的位置 $(i, j)$,然后将 和 分别加一,如果 $row[i] = n$ 或 $col[j] = m$,说明第 行或第 列已经被涂色,那么 就是我们要找的元素,返回…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 arr 和一个 m x n 的整数 矩阵 mat 。arr 和 mat 都包含范围 [1,m * n] 内的 所有 整数。
从下标 0 开始遍历 arr 中的每个下标 i ,并将包含整数 arr[i] 的 mat 单元格涂色。
请你找出 arr 中第一个使得 mat 的某一行或某一列都被涂色的元素,并返回其下标 i 。
示例 1:
输入:arr = [1,3,4,2], mat = [[1,4],[2,3]] 输出:2 解释:遍历如上图所示,arr[2] 在矩阵中的第一行或第二列上都被涂色。
示例 2:
输入:arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] 输出:3 解释:遍历如上图所示,arr[3] 在矩阵中的第二列上都被涂色。
提示:
m == mat.lengthn = mat[i].lengtharr.length == m * n1 <= m, n <= 1051 <= m * n <= 1051 <= arr[i], mat[r][c] <= m * narr中的所有整数 互不相同mat中的所有整数 互不相同
解题思路
方法一:哈希表 + 数组计数
我们用一个哈希表 记录每个元素在矩阵 中的位置,即 ,定义两个数组 和 分别记录每行和每列已经涂色的元素个数。
遍历数组 ,对于每个元素 ,我们找到其在矩阵 中的位置 ,然后将 和 分别加一,如果 或 ,说明第 行或第 列已经被涂色,那么 就是我们要找的元素,返回 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵 的行数和列数。
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
idx = {}
for i in range(m):
for j in range(n):
idx[mat[i][j]] = (i, j)
row = [0] * m
col = [0] * n
for k in range(len(arr)):
i, j = idx[arr[k]]
row[i] += 1
col[j] += 1
if row[i] == n or col[j] == m:
return k
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m * n) since we process each element of arr, marking the corresponding matrix cell and updating the row and column counts. Space complexity is O(m * n) to store the frequency of each row and column in hash maps. |
| 空间 | O(k) \equiv O(m\cdot n) |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates the use of a hash table for row/column tracking.
- question_mark
Candidate quickly identifies the optimization opportunity using a frequency array.
- question_mark
Candidate exhibits awareness of the constraints and chooses a solution that scales linearly with the matrix size.
常见陷阱
外企场景- error
Not efficiently tracking the painted rows and columns, leading to repeated scanning of the matrix.
- error
Failing to update row and column counters correctly, which might cause incorrect results.
- error
Not considering edge cases where the matrix might already have some painted rows or columns before processing the array.
进阶变体
外企场景- arrow_right_alt
How would the solution change if the goal were to paint the entire matrix before checking for a full row or column?
- arrow_right_alt
What if instead of marking the matrix, you were to use a different data structure to track the positions?
- arrow_right_alt
How would you optimize this if the matrix is sparsely populated with numbers?