LeetCode 题解工作台

奇数值单元格的数目

给你一个 m x n 的矩阵,最开始的时候,每个单元格中的值都是 0 。 另有一个二维索引数组 indices , indices[i] = [ri, ci] 指向矩阵中的某个位置,其中 ri 和 ci 分别表示指定的行和列( 从 0 开始编号 )。 对 indices[i] 所指向的每个位置,应同…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们创建一个矩阵 来存放操作的结果。对于 中的每一对 $(r_i, c_i)$,我们将矩阵第 行的所有数加 ,第 列的所有元素加 。 模拟结束后,遍历矩阵,统计奇数的个数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 m x n 的矩阵,最开始的时候,每个单元格中的值都是 0

另有一个二维索引数组 indicesindices[i] = [ri, ci] 指向矩阵中的某个位置,其中 rici 分别表示指定的行和列(0 开始编号)。

indices[i] 所指向的每个位置,应同时执行下述增量操作:

  1. ri 行上的所有单元格,加 1
  2. ci 列上的所有单元格,加 1

给你 mnindices 。请你在执行完所有 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 <= 50
  • 1 <= indices.length <= 100
  • 0 <= ri < m
  • 0 <= ci < n

 

进阶:你可以设计一个时间复杂度为 O(n + m + indices.length) 且仅用 O(n + m) 额外空间的算法来解决此问题吗?

lightbulb

解题思路

方法一:模拟

我们创建一个矩阵 gg 来存放操作的结果。对于 indices\textit{indices} 中的每一对 (ri,ci)(r_i, c_i),我们将矩阵第 rir_i 行的所有数加 11,第 cic_i 列的所有元素加 11

模拟结束后,遍历矩阵,统计奇数的个数。

时间复杂度 O(k×(m+n)+m×n)O(k \times (m + n) + m \times n),空间复杂度 O(m×n)O(m \times n)。其中 kkindices\textit{indices} 的长度。

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

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

奇数值单元格的数目题解:数组·数学 | LeetCode #1252 简单