304.Range Sum Query 2D - Immutable (M)
https://leetcode.com/problems/range-sum-query-2d-immutable/
Last updated
https://leetcode.com/problems/range-sum-query-2d-immutable/
Last updated
Given a 2D matrix matrix
, handle multiple queries of the following type:
Calculate the sum of the elements of matrix
inside the rectangle defined by its upper left corner (row1, col1)
and lower right corner (row2, col2)
.
Implement the NumMatrix class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrix matrix
.
int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements of matrix
inside the rectangle defined by its upper left corner (row1, col1)
and lower right corner (row2, col2)
.
Example 1:
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-105 <= matrix[i][j] <= 105
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
At most 104
calls will be made to sumRegion
.
比如说输入的 matrix
如下图:
那么 sumRegion([2,1,4,3])
就是图中红色的子矩阵,你需要返回该子矩阵的元素和 8。
这题的思路和一维数组中的前缀和是非常类似的,如下图:
如果我想计算红色的这个子矩阵的元素之和,可以用绿色矩阵减去蓝色矩阵减去橙色矩阵最后加上粉色矩阵,而绿蓝橙粉这四个矩阵有一个共同的特点,就是左上角就是 (0, 0)
原点。
那么我们可以维护一个二维 preSum
数组,专门记录以原点为顶点的矩阵的元素之和,就可以用几次加减运算算出任何一个子矩阵的元素和:
这样,sumRegion
函数的复杂度也用前缀和技巧优化到了 O(1)。