zoukankan      html  css  js  c++  java
  • LeetCode 304. Range Sum Query 2D

    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    Range Sum Query - Immutable一个道理,也是用二维数组dp存储历史信息, dp[i+1][j+1]表示 matrix[0][0] 到 matrix[i][j]的和,size不相同是为了简化i = 0 或者 j = 0时的特殊情况。

    生成dp时,dp[i][j]  = dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+matrix[i-1][j-1], 不包括本行的上面一个方块加上不包括本列的前一个方块减掉重叠部分在加上matrix的对应数。

    返回调用sumRegion(row1, col1, row2, col2)时,结果就是dp(row2,col2) - dp(row2,col1 - 1) - dp(row1 - 1,col2) + dp(row1 - 1,col1 - 1)

      -    -    +  

    1方块-2方块-3方块+4方块,4是多减掉的一部分.

    Time Complexity: NumMatrix, O(m*n). sumRegion, O(1). m = matrix.length, n = matrix[0].length.

    Space: O(m*n).

    AC Java:

     1 public class NumMatrix {
     2     int [][] dp;
     3     public NumMatrix(int[][] matrix) {
     4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
     5             return;
     6         }
     7         dp = new int[matrix.length+1][matrix[0].length+1];
     8         for(int i = 1; i<=matrix.length; i++){
     9             for(int j = 1; j<=matrix[0].length; j++){
    10                 dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i-1][j-1];
    11             }
    12         }
    13     }
    14 
    15     public int sumRegion(int row1, int col1, int row2, int col2) {
    16         return dp[row2+1][col2+1] - dp[row1][col2+1] - dp[row2+1][col1] + dp[row1][col1];
    17     }
    18 }
    19 
    20 
    21 // Your NumMatrix object will be instantiated and called as such:
    22 // NumMatrix numMatrix = new NumMatrix(matrix);
    23 // numMatrix.sumRegion(0, 1, 2, 3);
    24 // numMatrix.sumRegion(1, 2, 3, 4);

    跟上Range Sum Query 2D - Mutable.

  • 相关阅读:
    二分查找改遍
    条件运算符?:
    k倍区间
    分巧克力
    mm
    素数
    递归return
    确定一个域名使用的邮箱服务商
    mysql 存储过程一实例
    使用vmware 共享 windows下的文件夹 到 centos
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4961310.html
Copyright © 2011-2022 走看看