zoukankan      html  css  js  c++  java
  • [Coding Made Simple] Sum Query in 2D Immutable Array

    Given a 2D immutable array,  Write an efficient program to support any given sub-rectangle sum query in this 2D matrix.

    A simple solution is to add each entry inside the sub-rectangle. The runtime is O(n * m).

    The problem of this solution is that for a given 2D matrix, we always start from scratch to compute the sum of a sub-rectangle.

    Dynamic programming should be used to optimize the runtime.

    State: T[i][j]: the sum of sub rectangle with top left corner (0, 0) and bottom right corner (i - 1, j - 1).

    Function: T[i][j] = T[i - 1][j] + T[i][j - 1] + matrix[i - 1][j - 1] - T[i - 1][j - 1].

    Initialization: T[0][j] = T[i][0] = 0; 

    Answer:  given top left corner(x1, y1) and bottom right corner(x2, y2), 

        Sum of sub rectangle(x1, y1, x2, y2) is T[x2 + 1][y2 + 1] - T[x1][y2 + 1] - T[x2 + 1][y1] + T[x1][y1].

     1 public class SumQuery {
     2     private int[][] T;
     3     public SumQuery(int[][] matrix) {
     4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
     5             T = null;
     6         }
     7         T = new int[matrix.length + 1][matrix[0].length + 1];
     8         for(int i = 0; i < T.length; i++) {
     9             T[i][0] = 0;
    10         }
    11         for(int j = 0; j < T[0].length; j++) {
    12             T[0][j] = 0;
    13         }
    14         for(int i = 1; i < T.length; i++) {
    15             for(int j = 1; j < T[0].length; j++) {
    16                 T[i][j] = T[i - 1][j] + T[i][j - 1] + matrix[i - 1][j - 1] - T[i - 1][j - 1];
    17             }
    18         }
    19     }
    20     public int querySubRectangleSum(int x1, int y1, int x2, int y2) {
    21         x1++; y1++; x2++; y2++;
    22         return T[x2][y2] - T[x1 - 1][y2] - T[x2][y1 - 1] + T[x1 - 1][y1 - 1];
    23     }
    24 }
  • 相关阅读:
    Linux(CentOS)下squid代理服务器配置-五岳之巅
    用类实现二叉树
    django--02 模板的使用
    django --01 helloworld样例入门
    微指数爬虫
    celery_01 _celery安装启动
    python多线程几种方法实现
    crontab问题处理
    python可视化--matplotlib
    python网页爬虫--京东家电版块
  • 原文地址:https://www.cnblogs.com/lz87/p/7292280.html
Copyright © 2011-2022 走看看