当前位置:网站首页>Sword finger offer II 013 Sum of two-dimensional submatrix

Sword finger offer II 013 Sum of two-dimensional submatrix

2022-07-07 19:54:00 Jin huaixuan

Given a two-dimensional matrix matrix, Multiple requests of the following types :

Calculate the sum of the elements in its subrectangle , The upper left corner of the submatrix is (row1, col1) , The lower right corner is (row2, col2) .
Realization NumMatrix class :

NumMatrix(int[][] matrix)  Given an integer matrix matrix To initialize
int sumRegion(int row1, int col1, int row2, int col2)  Return to the upper left corner (row1, col1) 、 The lower right corner  (row2, col2)  The sum of the elements of the submatrix of .
 

Example 1:

Input : 
["NumMatrix","sumRegion","sumRegion","sumRegion"]
[[[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]
Output : 
[null, 8, 11, 12]

explain :
NumMatrix numMatrix = new NumMatrix([[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 ( The sum of the elements of the red rectangle )
numMatrix.sumRegion(1, 1, 2, 2); // return 11 ( The sum of the elements of the green rectangle )
numMatrix.sumRegion(1, 2, 2, 4); // return 12 ( Sum of elements in blue rectangle )

source : Power button (LeetCode)
link :https://leetcode.cn/problems/O4NDxx
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

java:

class NumMatrix {
    public int[][] mat;

    public NumMatrix(int[][] matrix) {
        // Given a two-dimensional array , Initialize the two-dimensional array 
        // [[3,0,1,4,2],
        //  [5,6,3,2,1],
        //  [1,2,0,1,5],
        //  [4,1,0,1,7],
        //  [1,0,3,0,5]]]
        this.mat = matrix;        
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        int total = 0;
        // Find the value of the given subscript 
        for(int i = row1;i <= row2 ; i++){
            for(int j = col1;j<=col2;j++){
                total += this.mat[i][j];
            }
        }
        return total;
    }
}

原网站

版权声明
本文为[Jin huaixuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071736515964.html