• 【LeetCode】304. 二维区域和检索 - 矩阵不可变


    304. 二维区域和检索 - 矩阵不可变(中等)

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    方法一:多个一维前缀和

    思路

    • 这道题是303. 区域和检索 - 数组不可变的进阶,第 303 题是在一维数组中做区域和检索,这道题是在二维矩阵中做区域和检索。
    • 第303 题中,初始化时对数组计算前缀和,每次检索即可在 O(1)的时间内得到结果。可以将第 303 题的做法应用于这道题,初始化时对矩阵的每一行计算前缀和,检索时对二维区域中的每一行计算子数组和,然后对每一行的子数组和计算总和
    • 具体实现方面,创建 m 行 n+1 列的二维数组 prefix,其中 m 和 n 分别是矩阵 matrix 的行数和列数, prefix 为 matrix 的前缀和数组。
    • 将sums的列数设为 n+1 的目的是为了方便计算每一行的子数组和,不需要对 col=0 的情况特殊处理

    代码

    class NumMatrix {
    public:
        vector<vector<int>> prefix;
        NumMatrix(vector<vector<int>>& matrix) : prefix(matrix.size(), vector<int>(matrix[0].size()+1, 0)){
            for(int i=0; i<matrix.size(); ++i){
                partial_sum(matrix[i].begin(), matrix[i].end(), prefix[i].begin()+1);
            }
        }
        
        int sumRegion(int row1, int col1, int row2, int col2) {
            int sum = 0;
            for(int i=row1; i<=row2; ++i){
                sum += prefix[i][col2+1] - prefix[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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    方法二: 积分图

    思路

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

    代码

    class NumMatrix {
    public:
        vector<vector<int>> prefix;
        NumMatrix(vector<vector<int>>& matrix) : prefix(matrix.size()+1, vector<int>(matrix[0].size()+1, 0)){
            for(int i=1; i<matrix.size()+1; ++i){
                for(int j=1; j<matrix[0].size()+1; ++j){
                    prefix[i][j] = prefix[i][j-1] + prefix[i-1][j] - prefix[i-1][j-1] + matrix[i-1][j-1];
                }
            }
        }
        
        int sumRegion(int row1, int col1, int row2, int col2) {
            return prefix[row2+1][col2+1] - prefix[row2+1][col1] - prefix[row1][col2+1] + prefix[row1][col1];
        }
    };
    
    /**
     * 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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    MySQL中分区与分表的区别
    【C++设计模式】详解装饰模式
    java创建对象的五种方式
    java计算机毕业设计Vue和mysql智能图书管理系统MyBatis+系统+LW文档+源码+调试部署
    c# 定时器
    [ROS笔记本]QT5问题cmake编译
    Kotlin基本语法
    【代码审计】——PHP项目类RCE及文件包含下载删除
    Java之Hashset(),LinkedHashset()
    Ant-Design-Pro-V5 :QueryFilter高级筛选组件、Table以及Pagination组件结合实现查询。
  • 原文地址:https://blog.csdn.net/weixin_43894455/article/details/131146431