My java solution, only used 6 ms.


  • 1
    W
    public class NumMatrix {
    
    int[][] sums;
    
    public NumMatrix(int[][] matrix) {
        if (matrix==null || matrix.length == 0 || matrix[0].length == 0)
            return;
        sums = new int[matrix.length + 1][matrix[0].length + 1];
        for (int i=0; i<matrix.length; i++){
            for (int j=0; j<matrix[0].length; j++){
                sums[i+1][j+1] = matrix[i][j] + sums[i+1][j] + sums[i][j+1] - sums[i][j];
            }
        }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (sums == null)
            return 0;
        if (++row2 > sums.length)
            row2 = sums.length;
        if (++col2 > sums[0].length)
            col2 = sums[0].length;
        return sums[row2][col2] - sums[row2][col1] - sums[row1][col2] + sums[row1][col1];
    }
    

    }


Log in to reply
 

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