LeetCode 题解工作台

子矩阵元素加 1

给你一个正整数 n ,表示最初有一个 n x n 、下标从 0 开始的整数矩阵 mat ,矩阵中填满了 0 。 另给你一个二维整数数组 query 。针对每个查询 query[i] = [row1 i , col1 i , row2 i , col2 i ] ,请你执行下述操作: 找出 左上角 为 …

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·matrix

bolt

答案摘要

二维差分数组是一种用于高效处理二维数组区间更新的技巧。我们可以通过维护一个与原矩阵大小相同的差分矩阵来实现对子矩阵的快速更新。 假设我们有一个二维差分矩阵 ,初始时所有元素均为 。对于每个查询 $[\textit{row1}, \textit{col1}, \textit{row2}, \textit{col2}]$,我们可以通过以下步骤更新差分矩阵:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n ,表示最初有一个 n x n 、下标从 0 开始的整数矩阵 mat ,矩阵中填满了 0 。

另给你一个二维整数数组 query 。针对每个查询 query[i] = [row1i, col1i, row2i, col2i] ,请你执行下述操作:

  • 找出 左上角(row1i, col1i)右下角(row2i, col2i) 的子矩阵,将子矩阵中的 每个元素1 。也就是给所有满足 row1i <= x <= row2icol1i <= y <= col2imat[x][y]1

返回执行完所有操作后得到的矩阵 mat

 

示例 1:

输入:n = 3, queries = [[1,1,2,2],[0,0,1,1]]
输出:[[1,1,0],[1,2,1],[0,1,1]]
解释:上图所展示的分别是:初始矩阵、执行完第一个操作后的矩阵、执行完第二个操作后的矩阵。
- 第一个操作:将左上角为 (1, 1) 且右下角为 (2, 2) 的子矩阵中的每个元素加 1 。 
- 第二个操作:将左上角为 (0, 0) 且右下角为 (1, 1) 的子矩阵中的每个元素加 1 。 

示例 2:

输入:n = 2, queries = [[0,0,1,1]]
输出:[[1,1],[1,1]]
解释:上图所展示的分别是:初始矩阵、执行完第一个操作后的矩阵。 
- 第一个操作:将矩阵中的每个元素加 1 。

 

提示:

  • 1 <= n <= 500
  • 1 <= queries.length <= 104
  • 0 <= row1i <= row2i < n
  • 0 <= col1i <= col2i < n
lightbulb

解题思路

方法一:二维差分

二维差分数组是一种用于高效处理二维数组区间更新的技巧。我们可以通过维护一个与原矩阵大小相同的差分矩阵来实现对子矩阵的快速更新。

假设我们有一个二维差分矩阵 diff\textit{diff},初始时所有元素均为 00。对于每个查询 [row1,col1,row2,col2][\textit{row1}, \textit{col1}, \textit{row2}, \textit{col2}],我们可以通过以下步骤更新差分矩阵:

  1. 在位置 (row1,col1)(\textit{row1}, \textit{col1})11
  2. 在位置 (row2+1,col1)(\textit{row2} + 1, \textit{col1})11,前提是 row2+1<n\textit{row2} + 1 < n
  3. 在位置 (row1,col2+1)(\textit{row1}, \textit{col2} + 1)11,前提是 col2+1<n\textit{col2} + 1 < n
  4. 在位置 (row2+1,col2+1)(\textit{row2} + 1, \textit{col2} + 1)11,前提是 row2+1<n\textit{row2} + 1 < ncol2+1<n\textit{col2} + 1 < n

完成所有查询后,我们需要通过前缀和的方式将差分矩阵转换回原矩阵。即,对于每个位置 (i,j)(i, j),我们计算:

mat[i][j]=diff[i][j]+(mat[i1][j] if i>0 else 0)+(mat[i][j1] if j>0 else 0)(mat[i1][j1] if i>0 and j>0 else 0)\textit{mat}[i][j] = \textit{diff}[i][j] + (\textit{mat}[i-1][j] \text{ if } i > 0 \text{ else } 0) + (\textit{mat}[i][j-1] \text{ if } j > 0 \text{ else } 0) - (\textit{mat}[i-1][j-1] \text{ if } i > 0 \text{ and } j > 0 \text{ else } 0)

时间复杂度 O(m+n2)O(m + n^2),其中 mmnn 分别是 queries\textit{queries} 的长度和给定的 nn。忽略答案的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:
        mat = [[0] * n for _ in range(n)]
        for x1, y1, x2, y2 in queries:
            mat[x1][y1] += 1
            if x2 + 1 < n:
                mat[x2 + 1][y1] -= 1
            if y2 + 1 < n:
                mat[x1][y2 + 1] -= 1
            if x2 + 1 < n and y2 + 1 < n:
                mat[x2 + 1][y2 + 1] += 1

        for i in range(n):
            for j in range(n):
                if i:
                    mat[i][j] += mat[i - 1][j]
                if j:
                    mat[i][j] += mat[i][j - 1]
                if i and j:
                    mat[i][j] -= mat[i - 1][j - 1]
        return mat
speed

复杂度分析

指标
时间complexity is O(n * q) using the row-wise prefix sum method, where q is the number of queries, compared to O(q * n^2) for naive updates. Space complexity is O(n^2) for the matrix plus O(n) extra for row differences.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks about handling multiple overlapping submatrices efficiently.

  • question_mark

    Mentions optimizing from naive element-wise updates to prefix sum techniques.

  • question_mark

    Checks understanding of Array plus Matrix patterns and row-level operations.

warning

常见陷阱

外企场景
  • error

    Trying to increment all elements directly for each query, causing TLE for large n.

  • error

    Forgetting to apply prefix sums after row-wise difference updates.

  • error

    Confusing row and column indices when applying submatrix increments.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Increment submatrices with arbitrary values instead of one.

  • arrow_right_alt

    Apply similar updates on non-square matrices or rectangular grids.

  • arrow_right_alt

    Count how many times each cell exceeds a threshold after multiple queries.

help

常见问题

外企场景

子矩阵元素加 1题解:数组·matrix | LeetCode #2536 中等