Skip to content

Commit 932f755

Browse files
authored
Create 304-range-sum-query-2d-immutable.js
1 parent 44e2b2d commit 932f755

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

304-range-sum-query-2d-immutable.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {number[][]} matrix
3+
*/
4+
const NumMatrix = function(matrix) {
5+
const dp = [];
6+
if (matrix.length == 0 || matrix[0].length == 0) return;
7+
for (let i = 0; i <= matrix.length; i++) {
8+
let t = new Array(matrix[0].length + 1).fill(0);
9+
dp.push(t);
10+
}
11+
12+
for (let i = 0; i < matrix.length; i++) {
13+
for (let j = 0; j < matrix[0].length; j++) {
14+
dp[i + 1][j + 1] = dp[i][j + 1] + dp[i + 1][j] + matrix[i][j] - dp[i][j];
15+
}
16+
}
17+
18+
this.cache = dp;
19+
};
20+
21+
/**
22+
* @param {number} row1
23+
* @param {number} col1
24+
* @param {number} row2
25+
* @param {number} col2
26+
* @return {number}
27+
*/
28+
NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
29+
const dp = this.cache;
30+
return (
31+
dp[row2 + 1][col2 + 1] -
32+
dp[row1][col2 + 1] -
33+
dp[row2 + 1][col1] +
34+
dp[row1][col1]
35+
);
36+
};
37+
38+
/**
39+
* Your NumMatrix object will be instantiated and called as such:
40+
* var obj = Object.create(NumMatrix).createNew(matrix)
41+
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
42+
*/

0 commit comments

Comments
 (0)