Simple JAVA solution


  • 0
    C
    public class NumMatrix {
        
        private int m;
        private int n;
        private int[][] sum;
    
        public NumMatrix(int[][] matrix)
        {
            this.m = matrix.length;
            if(m != 0)
            {
                this.n = matrix[0].length;
                
                sum = new int[m][n];
                
                for(int i = 0; i < m; i++)
                {
                    int s = 0;
                    for(int j = 0; j < n; j++)
                    {
                        s += matrix[i][j];
                        sum[i][j] = s;
                    }
                }
            }
            
        }
    
        public int sumRegion(int row1, int col1, int row2, int col2)
        {
            
            int s = 0;
            
            if(m == 0)
            {
                return 0;
            }
            
            for(int i = row1; i <= row2; i++)
            {
                if(col1 == 0)
                {
                    s += sum[i][col2];
                }
                else
                {
                    s += sum[i][col2] - sum[i][col1 - 1];
                }
            }
            
            return s;
        }
    }

Log in to reply
 

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