[LeetCode] Range Sum Query 2D - Immutable

304. Range Sum Query 2D - Immutable

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).
  • Time : O(nm) in initialize O(1) in sum
  • Space : O(nm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class NumMatrix {
vector<vector<int>> matrix;
int n, m;
int getOrZero(int y, int x) {
if(0 <= x and x < m and 0 <= y and y < n) {
return matrix[y][x];
}
return 0;
}
public:
NumMatrix(vector<vector<int>>& ma) {
n = ma.size();
m = ma[0].size();
matrix = ma;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
matrix[i][j] += getOrZero(i-1,j) + getOrZero(i,j-1) - getOrZero(i-1,j-1);
}
}

}

int sumRegion(int row1, int col1, int row2, int col2) {
return getOrZero(row2,col2) + getOrZero(row1-1,col1-1)
- getOrZero(row2,col1-1) - getOrZero(row1-1,col2);
}
};

/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/14/PS/LeetCode/range-sum-query-2d-immutable/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.