Java solution, how can I avoid those edge cases?


  • 0
    V
    int rows, columns;
    int[][] sums;
    int[][] matrix;
    
    public NumMatrix(int[][] matrix) {
        this.matrix = matrix;
        rows = matrix.length;
        if (rows>0 ){
        columns = matrix[0].length;
        sums = new int[rows][columns];
        for (int i=0;i<rows;i++) {
        	sums[i][0]=matrix[i][0];
            for (int j=1;j<columns;j++){
                sums[i][j]=sums[i][j-1]+matrix[i][j];
            }
        }
        }
    }
    
    public void update(int row, int col, int val) {
    	if (rows==0) return;
        int delta = val - matrix[row][col];
        for (int j=col;j<columns;j++){
            sums[row][j]+=delta;
        }
        matrix[row][col]=val;
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
    	if (rows==0) return 0;
        int sum=0;
        for (int i=row1;i<=row2;i++) {
            if (col1>0) {
                sum+=sums[i][col2]-sums[i][col1-1];
            }else {
                sum+=sums[i][col2];
            }
        }
        return sum;
    }

Log in to reply
 

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