Could anyone help me with my code?


  • 0
    T

    I submitted my code but it said "Runtime Error", but I couldn't find where's the problem.

      public class NumMatrix {
    // store the sum of the start to current in the same row
    int[][] rowSums;
    
    public NumMatrix(int[][] matrix) {
      int nrow = matrix.length;
      if(nrow == 0)
        return;
      int ncol = matrix[0].length;
      
      rowSums = new int[nrow][ncol];
      for(int i = 0; i < nrow; i++) {
        for(int j = 0; j < ncol; j++) {
          rowSums[i][j] = matrix[i][i] + (j == 0? 0: rowSums[i][j - 1]);
        }
      }
    }
    
    public void update(int row, int col, int val) {
      // the change value
      int diff = val - (rowSums[row][col] - (col == 0? 0: rowSums[row][col - 1]));
              
      for(int j = col; j < rowSums[0].length; j++) {
        rowSums[row][j] += diff;
      }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
      int sum = 0;
      
      for(int i = row1; i <= row2; i++) {
        sum += (rowSums[i][col2] - (col1 == 0? 0: rowSums[i][col1 - 1]));
      }
      
      return sum;
    }}

Log in to reply
 

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