[LeetCode][JavaScript]Range Sum Query 2D - Immutable
Range Sum Query 2D - Immutable
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] sumRegion(2, 1, 4, 3) -> 8 sumRegion(1, 1, 2, 2) -> 11 sumRegion(1, 2, 2, 4) -> 12
Note:
- You may assume that the matrix does not change.
- There are many calls to sumRegion function.
- You may assume that row1 ≤ row2 and col1 ≤ col2.
https://leetcode.com/problems/range-sum-query-2d-immutable/
矩阵求和,给定数组不会变,求和方法会反复调用多次。
维护一个数组,dp(i,j)的值就是从(0,0)到(i,j)的和。
调用sumRegion(row1, col1, row2, col2)时,结果就是dp(row2,col2) - dp(row2,col1 - 1) - dp(row1 - 1,col2) + dp(row1 - 1,col1 - 1)。
- - +
1 /** 2 * @constructor 3 * @param {number[][]} matrix 4 */ 5 var NumMatrix = function(matrix) { 6 this.dp = []; 7 var i, j, top, rowSum; 8 var rowLen = matrix[0] ? matrix[0].length : 0; 9 for(i = 0; i < matrix.length; i++){ 10 rowSum = 0; 11 for(j = 0; j < rowLen; j++){ 12 if(!this.dp[i]){ 13 this.dp[i] = []; 14 } 15 rowSum += matrix[i][j]; 16 top = this.dp[i - 1] && this.dp[i - 1][j] ? this.dp[i - 1][j] : 0; 17 this.dp[i][j] = top + rowSum; 18 } 19 } 20 }; 21 22 /** 23 * @param {number} row1 24 * @param {number} col1 25 * @param {number} row2 26 * @param {number} col2 27 * @return {number} 28 */ 29 NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) { 30 var left = this.dp[row2][col1 - 1] ? this.dp[row2][col1 - 1] : 0; 31 var top = this.dp[row1 - 1] ? this.dp[row1 - 1][col2] : 0; 32 var topLeft = this.dp[row1 - 1] && this.dp[row1 - 1][col1 - 1] ? this.dp[row1 - 1][col1 - 1] : 0; 33 return this.dp[row2][col2] - left - top + topLeft; 34 };