C# - row sum (sub-optimal)


  • 0
    private int[,] sums = null;
    private int rows = 0;
    private int cols = 0;
    
    public NumMatrix(int[,] matrix) 
    {
        this.rows = matrix.GetLength(0);
        this.cols = matrix.GetLength(1);
        this.sums = new int[this.rows,this.cols];
        
        for (int r = rows - 1; r >= 0; r--)
        {
            int sum = 0;
            for (int c = cols - 1; c >= 0; c--)
            {
                sum += matrix[r,c];
                this.sums[r,c] = sum;
            }
        }
    }
    
    public int SumRegion(int row1, int col1, int row2, int col2) 
    {
        int sum = 0;
        int endCol = col2 + 1 < this.cols ? col2 + 1 : -1;
        for (int r = row1; r <= row2; r++)
        {
            sum += this.sums[r,col1] - (endCol > 0 ? this.sums[r,endCol] : 0);
        }
        return sum;
    }

Log in to reply
 

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