LeetCode 题解工作台
奇数值单元格的数目
给你一个 m x n 的矩阵,最开始的时候,每个单元格中的值都是 0 。 另有一个二维索引数组 indices , indices[i] = [ri, ci] 指向矩阵中的某个位置,其中 ri 和 ci 分别表示指定的行和列( 从 0 开始编号 )。 对 indices[i] 所指向的每个位置,应同…
3
题型
4
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们创建一个矩阵 来存放操作的结果。对于 中的每一对 $(r_i, c_i)$,我们将矩阵第 行的所有数加 ,第 列的所有元素加 。 模拟结束后,遍历矩阵,统计奇数的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个 m x n 的矩阵,最开始的时候,每个单元格中的值都是 0。
另有一个二维索引数组 indices,indices[i] = [ri, ci] 指向矩阵中的某个位置,其中 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。
对 indices[i] 所指向的每个位置,应同时执行下述增量操作:
ri行上的所有单元格,加1。ci列上的所有单元格,加1。
给你 m、n 和 indices 。请你在执行完所有 indices 指定的增量操作后,返回矩阵中 奇数值单元格 的数目。
示例 1:

输入:m = 2, n = 3, indices = [[0,1],[1,1]] 输出:6 解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。 第一次增量操作后得到 [[1,2,1],[0,1,0]]。 最后的矩阵是 [[1,3,1],[1,3,1]],里面有 6 个奇数。
示例 2:

输入:m = 2, n = 2, indices = [[1,1],[0,0]] 输出:0 解释:最后的矩阵是 [[2,2],[2,2]],里面没有奇数。
提示:
1 <= m, n <= 501 <= indices.length <= 1000 <= ri < m0 <= ci < n
进阶:你可以设计一个时间复杂度为 O(n + m + indices.length) 且仅用 O(n + m) 额外空间的算法来解决此问题吗?
解题思路
方法一:模拟
我们创建一个矩阵 来存放操作的结果。对于 中的每一对 ,我们将矩阵第 行的所有数加 ,第 列的所有元素加 。
模拟结束后,遍历矩阵,统计奇数的个数。
时间复杂度 ,空间复杂度 。其中 为 的长度。
class Solution:
def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
g = [[0] * n for _ in range(m)]
for r, c in indices:
for i in range(m):
g[i][c] += 1
for j in range(n):
g[r][j] += 1
return sum(v % 2 for row in g for v in row)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests understanding of matrix manipulation and array operations.
- question_mark
Assesses ability to optimize solutions and recognize inefficiencies in naive approaches.
- question_mark
Evaluates problem-solving skills in simulating operations and managing matrix states efficiently.
常见陷阱
外企场景- error
Misunderstanding the task and applying increments directly to the matrix rather than simulating row/column operations.
- error
Not accounting for the fact that multiple increments can affect the same row and column multiple times.
- error
Failing to optimize the approach, leading to unnecessary computations and higher time complexity.
进阶变体
外企场景- arrow_right_alt
What if the matrix is much larger, and performance becomes an issue?
- arrow_right_alt
How would the solution change if we had to also return the final matrix, not just the count of odd cells?
- arrow_right_alt
What if the number of operations is significantly higher, affecting performance?