Skip to content

Commit 329563b

Browse files
committed
Runtime: 317 ms (Top 73.49%) | Memory: 75.60 MB (Top 73.49%)
1 parent f078f1c commit 329563b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Runtime: 317 ms (Top 73.49%) | Memory: 75.60 MB (Top 73.49%)
2+
3+
var NumMatrix = function(matrix) {
4+
5+
let R = matrix.length
6+
let C = matrix[0].length
7+
8+
this.sumMatrix = Array.from({length: R + 1}, () => new Array(C + 1).fill(0))
9+
10+
for (let r = 0; r < R; r++) {
11+
12+
let prefix = 0
13+
14+
for (let c = 0; c < C; c++) {
15+
16+
prefix += matrix[r][c]
17+
18+
let above = this.sumMatrix[r][c + 1]
19+
20+
this.sumMatrix[r + 1][c + 1] = prefix + above
21+
}
22+
23+
}
24+
25+
};
26+
27+
NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
28+
29+
row1 = row1 + 1
30+
col1 = col1 + 1
31+
row2 = row2 + 1
32+
col2 = col2 + 1
33+
34+
let bottomRight = this.sumMatrix[row2][col2]
35+
let above = this.sumMatrix[row1 - 1][col2]
36+
let left = this.sumMatrix[row2][col1 - 1]
37+
let topLeft = this.sumMatrix[row1 - 1][col1 - 1]
38+
39+
return bottomRight - above - left + topLeft
40+
41+
};
42+
43+
/**
44+
* Your NumMatrix object will be instantiated and called as such:
45+
* var obj = new NumMatrix(matrix)
46+
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
47+
*/

0 commit comments

Comments
 (0)