【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);
 */
相关推荐
小月球~4 小时前
天梯赛 · 并查集
数据结构·算法
仍然.4 小时前
算法题目---模拟
java·javascript·算法
6Hzlia5 小时前
【Hot 100 刷题计划】 LeetCode 118. 杨辉三角 | C++ 动态规划题解
c++·leetcode·动态规划
潇冉沐晴6 小时前
DP——背包DP
算法·背包dp
GIOTTO情7 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃7 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾7 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic7 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
副露のmagic7 小时前
字符串章节 leetcode 思路&实现
windows·python·leetcode
csuzhucong7 小时前
puzzle(1037)黑白、黑白棋局
算法