Skip to content

Commit cbdddf2

Browse files
committed
Add solution #304
1 parent 46bf946 commit cbdddf2

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@
248248
300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium|
249249
301|[Remove Invalid Parentheses](./0301-remove-invalid-parentheses.js)|Hard|
250250
303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy|
251+
304|[Range Sum Query 2D - Immutable](./0304-range-sum-query-2d-immutable.js)|Medium|
251252
306|[Additive Number](./0306-additive-number.js)|Medium|
252253
309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
253254
315|[Count of Smaller Numbers After Self](./0315-count-of-smaller-numbers-after-self.js)|Hard|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 304. Range Sum Query 2D - Immutable
3+
* https://leetcode.com/problems/range-sum-query-2d-immutable/
4+
* Difficulty: Medium
5+
*
6+
* Given a 2D matrix matrix, handle multiple queries of the following type:
7+
* - Calculate the sum of the elements of matrix inside the rectangle defined by its upper
8+
* left corner (row1, col1) and lower right corner (row2, col2).
9+
*
10+
* Implement the NumMatrix class:
11+
* - NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
12+
* - int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements
13+
* of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower
14+
* right corner (row2, col2).
15+
*
16+
* You must design an algorithm where sumRegion works on O(1) time complexity.
17+
*/
18+
19+
/**
20+
* @param {number[][]} matrix
21+
*/
22+
var NumMatrix = function(matrix) {
23+
this.sums = new Array(matrix.length + 1).fill().map(() => {
24+
return new Array(matrix[0].length + 1).fill(0);
25+
});
26+
27+
for (let i = 1; i <= matrix.length; i++) {
28+
for (let j = 1; j <= matrix[0].length; j++) {
29+
this.sums[i][j] = matrix[i - 1][j - 1] + this.sums[i - 1][j]
30+
+ this.sums[i][j - 1] - this.sums[i - 1][j - 1];
31+
}
32+
}
33+
};
34+
35+
/**
36+
* @param {number} row1
37+
* @param {number} col1
38+
* @param {number} row2
39+
* @param {number} col2
40+
* @return {number}
41+
*/
42+
NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
43+
return this.sums[row2 + 1][col2 + 1] - this.sums[row2 + 1][col1]
44+
- this.sums[row1][col2 + 1] + this.sums[row1][col1];
45+
};

0 commit comments

Comments
 (0)