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

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

方法:一维前缀和

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

具体实现方面,创建 m 行 n+1 列的二维数组 sums,其中 m和 n 分别是矩阵 matrix 的行数和列数,sumsi为 matrixi 的前缀和数组。将 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);
 */
相关推荐
罗西的思考6 小时前
【Agentic RL】Dressage Staleness 控制深度分析
人工智能·算法·机器学习
quaer6 小时前
弗洛伊德算法--判圈法寻找环的入口O(n) O(1)
数据结构·算法
文丑颜不良啊7 小时前
LeetCode51~75题目解析
leetcode
高晶7 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy7 小时前
大数计算思路
算法
高晶8 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗8 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李8 小时前
反向传播计算梯度举例
算法
niyongsheng8 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger9 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法