• [LeetCode][JavaScript]Range Sum Query 2D


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

    Range Sum Query 2D
    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:

    1. You may assume that the matrix does not change.
    2. There are many calls to sumRegion function.
    3. 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 };
  • 相关阅读:
    nat
    ICE协议下NAT穿越的实现(STUN&TURN)
    比特币源码分析--端口映射
    IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别(百度)
    从数据的角度带你深入了解IPFS
    IPFS 到底是怎么工作的?
    从数据的角度带你深入了解IPFS
    IPFS
    IPFS中文简介
    bootstrap 表单验证 dem
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4958928.html
Copyright © 2020-2023  润新知