LeetCode 题解工作台
二维区域和检索 - 矩阵不可变
给定一个二维矩阵 matrix , 以下类型的多个请求: 计算其子矩形范围内元素的总和,该子矩阵的 左上角 为 (row1, col1) , 右下角 为 (row2, col2) 。 实现 NumMatrix 类: NumMatrix(int[][] matrix) 给定整数矩阵 matrix 进行…
4
题型
8
代码语言
3
相关题
当前训练重点
中等 · 前缀和
答案摘要
我们用 $s[i + 1][j + 1]$ 表示第 行第 列左上部分所有元素之和,下标 和 均从 开始。可以得到以下前缀和公式: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给定一个二维矩阵 matrix,以下类型的多个请求:
- 计算其子矩形范围内元素的总和,该子矩阵的 左上角 为
(row1, col1),右下角 为(row2, col2)。
实现 NumMatrix 类:
NumMatrix(int[][] matrix)给定整数矩阵matrix进行初始化int sumRegion(int row1, int col1, int row2, int col2)返回 左上角(row1, col1)、右下角(row2, col2)所描述的子矩阵的元素 总和 。
示例 1:

输入: ["NumMatrix","sumRegion","sumRegion","sumRegion"] [[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]] 输出: [null, 8, 11, 12] 解释: NumMatrix numMatrix = new NumMatrix([[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (红色矩形框的元素总和) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (绿色矩形框的元素总和) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和)
提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 200-105 <= matrix[i][j] <= 1050 <= row1 <= row2 < m0 <= col1 <= col2 < n- 最多调用
104次sumRegion方法
解题思路
方法一:二维前缀和
我们用 表示第 行第 列左上部分所有元素之和,下标 和 均从 开始。可以得到以下前缀和公式:
那么分别以 和 为左上角和右下角的矩形的元素之和为:
我们在初始化方法中预处理出前缀和数组 ,在查询方法中直接返回上述公式的结果即可。
初始化的时间复杂度为 ,查询的时间复杂度为 。空间复杂度为 。
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
m, n = len(matrix), len(matrix[0])
self.s = [[0] * (n + 1) for _ in range(m + 1)]
for i, row in enumerate(matrix):
for j, v in enumerate(row):
self.s[i + 1][j + 1] = (
self.s[i][j + 1] + self.s[i + 1][j] - self.s[i][j] + v
)
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
return (
self.s[row2 + 1][col2 + 1]
- self.s[row2 + 1][col1]
- self.s[row1][col2 + 1]
+ self.s[row1][col1]
)
# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidates should demonstrate an understanding of prefix sums and how to apply them to a 2D matrix.
- question_mark
Look for familiarity with space and time trade-offs, especially regarding the need to store and update the prefix sum matrix.
- question_mark
Pay attention to how candidates approach the optimization of the query time, ensuring O(1) complexity for sumRegion.
常见陷阱
外企场景- error
Failing to precompute the prefix sum matrix, leading to inefficient solutions.
- error
Incorrectly handling the boundaries of the matrix when calculating sumRegion, which can result in out-of-bounds errors.
- error
Overcomplicating the solution by not focusing on the O(1) query requirement, instead implementing less efficient methods.
进阶变体
外企场景- arrow_right_alt
Allowing for dynamic updates to the matrix, which would require modifying the prefix sum after each update.
- arrow_right_alt
Handling queries for different types of submatrices, such as those that cover rows or columns.
- arrow_right_alt
Improving space efficiency by using rolling sums or other data structures for large matrices.