[LeetCode] 304. Range Sum Query 2D - Immutable

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [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]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

二维区域和检索 - 矩阵不可变。

给定一个二维矩阵 matrix,以下类型的多个请求:

计算其子矩形范围内元素的总和,该子矩阵的 左上角 为 (row1, col1) ,右下角 为 (row2, col2) 。
实现 NumMatrix 类:

NumMatrix(int[][] matrix) 给定整数矩阵 matrix 进行初始化
int sumRegion(int row1, int col1, int row2, int col2) 返回 左上角 (row1, col1) 、右下角 (row2, col2) 所描述的子矩阵的元素 总和 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/range-sum-query-2d-immutable
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。

上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。

303题类似,思路也是前缀和。这里因为 input 矩阵不能修改,我们必须创建一个额外的二维数组记录结果。我这里给一个很好的图示帮助理解。

sumRegion(A,DsumRegion(O,D) - sumRegion(O,E) - sumRegion(O,F) + sumRegion(O,G)

我们先用一个二维矩阵 grid 记录了整个 input 矩阵的二维前缀和。如果要求整个二维矩阵的前缀和 sumRegion(O, D), 可以直接返回 grid[x + 1][y + 1],但是上面这个式子记忆的时候下标容易出错,我是这样记的。

OD - OE - OF + OG,中间减去的那两个部分一个需要横坐标 - 1,一个需要纵坐标 - 1

[x2 + 1, y2 + 1] - [x1, y2 + 1] - [x2 + 1. y1] + [x1, y1]

时间O(mn)

空间O(mn)

Java实现

 1 class NumMatrix {
 2     // grid[i+1][j+1] = sumRegion(0,0,i,j)
 3     int[][] grid;
 4     
 5     public NumMatrix(int[][] matrix) {
 6         // corner case
 7         if (matrix == null || matrix.length == 0) {
 8             return;
 9         }
10         int m = matrix.length;
11         int n = matrix[0].length;
12         grid = new int[m + 1][n + 1];
13         for (int i = 0; i < m; i++) {
14             for (int j = 0; j < n; j++) {
15                 grid[i + 1][j + 1] = grid[i + 1][j] + grid[i][j + 1] + matrix[i][j] - grid[i][j];
16             }
17         }
18     }
19     
20     public int sumRegion(int row1, int col1, int row2, int col2) {
21         // [x2 + 1, y2 + 1] - [x1, y2 + 1] - [x2 + 1. y1] + [x1, y1]
22         return grid[row2 + 1][col2 + 1] - grid[row1][col2 + 1] - grid[row2 + 1][col1] + grid[row1][col1];
23     }
24 }
25 
26 /**
27  * Your NumMatrix object will be instantiated and called as such:
28  * NumMatrix obj = new NumMatrix(matrix);
29  * int param_1 = obj.sumRegion(row1,col1,row2,col2);
30  */

 

相关题目

303. Range Sum Query - Immutable

304. Range Sum Query 2D - Immutable

LeetCode 题目总结

posted @ 2021-03-02 01:20  CNoodle  阅读(225)  评论(0编辑  收藏  举报