@@ -59,11 +59,21 @@ numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和)
59
59
60
60
** 方法一:二维前缀和**
61
61
62
- ` s[i + 1][j + 1] ` 表示第 i 行第 j 列左上部分所有元素之和,其中 i, j 下标从 0 开始。
62
+ 我们用 $ s[ i + 1] [ j + 1 ] $ 表示第 $i$ 行第 $j$ 列左上部分所有元素之和,下标 $i$ 和 $j$ 均从 $0$ 开始。可以得到以下前缀和公式:
63
63
64
- 则 ` s[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j] + nums[i][j] ` 。
64
+ $$
65
+ s[i + 1][j + 1] = s[i + 1][j] + s[i][j + 1] - s[i][j] + nums[i][j]
66
+ $$
65
67
66
- 以 (x1, y1) 为左上角,(x2, y2) 为右下角的子矩阵和 ` sub = s[x2 + 1][y2 + 1] - s[x2 + 1][y1] - s[x1][y2 + 1] + s[x1][y1] ` 。
68
+ 那么分别以 $(x_1, y_1)$ 和 $(x_2, y_2)$ 为左上角和右下角的矩形的元素之和为:
69
+
70
+ $$
71
+ s[x_2 + 1][y_2 + 1] - s[x_2 + 1][y_1] - s[x_1][y_2 + 1] + s[x_1][y_1]
72
+ $$
73
+
74
+ 我们在初始化方法中预处理出前缀和数组 $s$,在查询方法中直接返回上述公式的结果即可。
75
+
76
+ 初始化的时间复杂度为 $O(m\times n)$,查询的时间复杂度为 $O(1)$。
67
77
68
78
<!-- tabs:start -->
69
79
@@ -231,6 +241,44 @@ NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) {
231
241
*/
232
242
```
233
243
244
+ ### ** TypeScript**
245
+
246
+ ``` ts
247
+ class NumMatrix {
248
+ private s: number [][];
249
+
250
+ constructor (matrix : number [][]) {
251
+ const m = matrix .length ;
252
+ const n = matrix [0 ].length ;
253
+ this .s = new Array (m + 1 ).fill (0 ).map (() => new Array (n + 1 ).fill (0 ));
254
+ for (let i = 0 ; i < m ; ++ i ) {
255
+ for (let j = 0 ; j < n ; ++ j ) {
256
+ this .s [i + 1 ][j + 1 ] =
257
+ this .s [i + 1 ][j ] +
258
+ this .s [i ][j + 1 ] -
259
+ this .s [i ][j ] +
260
+ matrix [i ][j ];
261
+ }
262
+ }
263
+ }
264
+
265
+ sumRegion(row1 : number , col1 : number , row2 : number , col2 : number ): number {
266
+ return (
267
+ this .s [row2 + 1 ][col2 + 1 ] -
268
+ this .s [row2 + 1 ][col1 ] -
269
+ this .s [row1 ][col2 + 1 ] +
270
+ this .s [row1 ][col1 ]
271
+ );
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Your NumMatrix object will be instantiated and called as such:
277
+ * var obj = new NumMatrix(matrix)
278
+ * var param_1 = obj.sumRegion(row1,col1,row2,col2)
279
+ */
280
+ ```
281
+
234
282
### ** ...**
235
283
236
284
```
0 commit comments