|
| 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