304. Range Sum Query 2D - Immutable

来源:互联网 发布:js触发submit按钮 编辑:程序博客网 时间:2024/05/16 07:59

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) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(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.
动态规划,把每个点的左上方区域的和都计算出来,利用容斥原理计算对应区域的值;需要注意当row1==0 col1==0 时的越界问题;也可以采用多加一个空行空列的方法

避免越界的问题:如  https://discuss.leetcode.com/topic/33841/very-clean-and-fast-java-solution

http://blog.csdn.net/zdavb/article/details/49807841

类似问题很多:303. Range Sum Query - Immutable 

307. Range Sum Query - Mutable


public class NumMatrix {int [][]SumMatrix;boolean val=false;    public NumMatrix(int[][] matrix) {        // int ii=0,jj=0;        // while(jj<matrix[0].length){        //     matrix[0][jj]=matrix        // }        if(matrix.length==0||matrix==null) { val=true;return ;}        for(int i=1;i<matrix.length;i++){            matrix[i][0]=matrix[i-1][0]+matrix[i][0];        }        for(int i=1;i<matrix[0].length;i++){             matrix[0][i]=matrix[0][i-1]+matrix[0][i];        }        for(int i=1;i<matrix.length;i++){            for(int j=1;j<matrix[0].length;j++){                matrix[i][j]=matrix[i][j]+matrix[i-1][j]+matrix[i][j-1]-matrix[i-1][j-1];            }        }        SumMatrix=matrix;    }    public int sumRegion(int row1, int col1, int row2, int col2) {        if(val) return 0;        if(row1==0&&col1==0) return SumMatrix[row2][col2];        if(row1==0) return SumMatrix[row2][col2]-SumMatrix[row2][col1-1];        if(col1==0) return SumMatrix[row2][col2]-SumMatrix[row1-1][col2];        return SumMatrix[row2][col2]-SumMatrix[row1-1][col2]-SumMatrix[row2][col1-1]+SumMatrix[row1-1][col1-1];    }}// Your NumMatrix object will be instantiated and called as such:// NumMatrix numMatrix = new NumMatrix(matrix);// numMatrix.sumRegion(0, 1, 2, 3);// numMatrix.sumRegion(1, 2, 3, 4);

0 0
原创粉丝点击