二维区域和检索

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14473318.html

二维区域和检索

题目链接:https://leetcode-cn.com/problems/range-sum-query-2d-immutable/submissions/

题目

给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2) 。


上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。

 

示例:

给定 matrix = [
[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]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

题解

此题突破点在于需要定义一个全局的二维数组,因为给定的数组和给的范围不在一个函数中,而二维数组肯定和范围有关,所以需要定义一个全局的二维数组,在第一个函数中给二维数组赋值,在第二个函数需要满足条件的数组和。

代码

class NumMatrix {
    int arr[][];
    int sum;
    public NumMatrix(int[][] matrix) {
         int row=matrix.length;
       
         if(row>0)
         {
               int col=matrix[0].length;
             arr=new int [row][col];
         for(int i=0;i<row;i++)
         {
            for(int j=0;j<matrix[i].length;j++){
                arr[i][j]=matrix[i][j];
            }
         }
          }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum=0;
        for(int i=row1;i<=row2;i++){
            for(int j=col1;j<=col2;j++)
            {
               sum=sum+arr[i][j];
            }
        }
        return sum;
    }
}

 

结果

 

posted @ 2021-03-03 11:12  萍2樱释  阅读(86)  评论(0编辑  收藏  举报