其他分享
首页 > 其他分享> > 304. 二维区域和检索 - 矩阵不可变

304. 二维区域和检索 - 矩阵不可变

作者:互联网

class NumMatrix {

    private int[][] matrix;

    public NumMatrix(int[][] matrix) {
        this.matrix = matrix;
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i = row1; i <= row2; i++) {
            for (int j = col1; j <= col2; j++) {
                sum += matrix[i][j];
            }
        }
        return sum;
    }
}
class NumMatrix {

    private int[][] numMatrix;

    public NumMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            numMatrix = new int[0][0];
            return;
        }
        numMatrix = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if(i==0 && j == 0) {
                    numMatrix[i][j] = matrix[i][j];
                } else if(i==0 && j != 0) {
                    numMatrix[i][j] = numMatrix[i][j-1] + matrix[i][j];
                } else if (i!=0 && j == 0) {
                    numMatrix[i][j] = numMatrix[i-1][j] + matrix[i][j];
                } else {
                    numMatrix[i][j] = numMatrix[i][j-1] + numMatrix[i-1][j] - numMatrix[i-1][j-1] + matrix[i][j];
                }
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (row1 == 0 && col1 == 0) {
            return numMatrix[row2][col2];
        } else if (row1 == 0) {
            return numMatrix[row2][col2] - numMatrix[row2][col1-1];
        } else if (col1 == 0) {
            return numMatrix[row2][col2] - numMatrix[row1-1][col2];
        } else {
            return numMatrix[row2][col2] - numMatrix[row2][col1-1] - numMatrix[row1-1][col2] + numMatrix[row1-1][col1-1];
        }
    }
}

标签:检索,row1,row2,matrix,int,304,col2,矩阵,numMatrix
来源: https://www.cnblogs.com/lasclocker/p/11337134.html