【LeetCode-剑指offer】-- 13.二维区域和检索-矩阵不可变

13.二维区域和检索-矩阵不可变

方法:一维前缀和

初始化时对矩阵的每一行计算前缀和,检索时对二维区域中的每一行计算子数组和,然后对每一行的子数组和计算总和。

具体实现方面,创建 m 行 n+1 列的二维数组 sums,其中 m和 n 分别是矩阵 matrix 的行数和列数,sums[i]为 matrix[i] 的前缀和数组。将 sums 的列数设为 n+1 的目的是为了方便计算每一行的子数组和,不需要对 col1=0的情况特殊处理。

java 复制代码
class NumMatrix {
    int[][] sums;
    public NumMatrix(int[][] matrix) {
        int m = matrix.length;
        if(m > 0){
            int n = matrix[0].length;
            sums = new int[m][n+1];
            for(int i = 0;i<m;i++){
                for(int j = 0;j<n;j++){
                    //对二维区域中每一行计算子数组和,对每一行的子数组计算总和
                    sums[i][j+1] = sums[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++){
            sum += sums[i][col2+1] - sums[i][col1];
        }
        return sum;
    }
}

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * int param_1 = obj.sumRegion(row1,col1,row2,col2);
 */
相关推荐
孤飞1 天前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家1 天前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
csdn_aspnet1 天前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp1 天前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium1 天前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5631 天前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮1 天前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11011 天前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先
会编程的土豆1 天前
01背包与完全背包详解
开发语言·数据结构·c++·算法
汀、人工智能1 天前
[特殊字符] 第86课:最大正方形
数据结构·算法·数据库架构·图论·bfs·最大正方形