Simple Java Solution. Beats 80%


  • 1
    K
    public class NumMatrix {
    
        int[][] m;
        public NumMatrix(int[][] matrix) {
            m = matrix;
            prepareMatrix(m);
        }
        
        public int sumRegion(int row1, int col1, int row2, int col2) {
            int sum = 0;
            while(row1 <= row2) {
                if(col1 == 0) sum += m[row1][col2];
                else sum += m[row1][col2] - m[row1][col1-1];
                row1++;
            }
            return sum;
        }
        
        private void prepareMatrix(int[][] m) {
            for(int r=0; r<m.length; r++) {
                for(int c=0; c<m[0].length; c++) {
                    if(c==0) m[r][c] = m[r][c];
                    else m[r][c] += m[r][c-1];
                }
            }
        }
    }
    

Log in to reply
 

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