Java Solution Maintaining Row Sum


  • 1
    B
    public class NumMatrix {
    
    private int[][] rowSum;
    private int[][] matrix;
    
    public NumMatrix(int[][] matrix) {
        int m = matrix.length;
        if (m == 0 || matrix[0].length == 0) return;
        int n = matrix[0].length;
        
        this.matrix = matrix;
        rowSum = new int[m][n + 1];
        for (int i = 0; i < m; i++) {
            for (int j = 1; j <= n; j++) {
                rowSum[i][j] = rowSum[i][j - 1] + matrix[i][j - 1];
            }
        }
    }
    
    public void update(int row, int col, int val) {
        int diff = val - matrix[row][col];
        for (int j = col + 1; j <= matrix[0].length; j++) {
            rowSum[row][j] += diff;
        }
        matrix[row][col] = val;
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i = row1; i <= row2; i++) {
            sum += rowSum[i][col2 + 1] - rowSum[i][col1];
        }
        return sum;
    }
    

    }

    // Your NumMatrix object will be instantiated and called as such:
    // NumMatrix numMatrix = new NumMatrix(matrix);
    // numMatrix.sumRegion(0, 1, 2, 3);
    // numMatrix.update(1, 1, 10);
    // numMatrix.sumRegion(1, 2, 3, 4);


Log in to reply
 

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