My Java Solution


  • 0
    R
    int[][] matrix;
    public NumMatrix(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        for (int j = 1; j < matrix[0].length; j++) {
            matrix[0][j] += matrix[0][j-1];
        }
        for (int i = 1; i < matrix.length; i++) {
            matrix[i][0] += matrix[i-1][0];   
        }
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                matrix[i][j] += matrix[i-1][j] - matrix[i-1][j-1] + matrix[i][j-1];
            }
        }
        this.matrix = matrix;
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        int top = row1 == 0 ? 0 : matrix[row1-1][col2];
        int left = col1 == 0 ? 0 : matrix[row2][col1-1];
        int makeup = row1 != 0 && col1 != 0 ? matrix[row1-1][col1-1] : 0;
        return matrix[row2][col2] - top - left + makeup;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.