【数据结构-二维前缀和】力扣304. 二维区域和检索 - 矩阵不可变

给定一个二维矩阵 matrix,以下类型的多个请求:

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

实现 NumMatrix 类:

NumMatrix(int\[\]\[\] matrix) 给定整数矩阵 matrix 进行初始化

int sumRegion(int row1, int col1, int row2, int col2) 返回 左上角 (row1, col1) 、右下角 (row2, col2) 所描述的子矩阵的元素 总和 。

输入:

"NumMatrix","sumRegion","sumRegion","sumRegion"

\[\[\[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\]\]\],\[2,1,4,3\],\[1,1,2,2\],\[1,2,2,4\]

输出:

null, 8, 11, 12

解释:

NumMatrix numMatrix = new NumMatrix(\[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]);

numMatrix.sumRegion(2, 1, 4, 3); // return 8 (红色矩形框的元素总和)

numMatrix.sumRegion(1, 1, 2, 2); // return 11 (绿色矩形框的元素总和)

numMatrix.sumRegion(1, 2, 2, 4); // return 12 (蓝色矩形框的元素总和)

示例 1:

cpp 复制代码
class NumMatrix {
public:
    vector<vector<int>> sums;
    NumMatrix(vector<vector<int>>& matrix) {
        int m = matrix.size();
        if (m > 0) {
            int n = matrix[0].size();
            sums.resize(m + 1, vector<int>(n + 1));
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    sums[i + 1][j + 1] = sums[i][j + 1] + sums[i + 1][j] - sums[i][j] + matrix[i][j];
                }
            }
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        return sums[row2+1][col2+1] - sums[row2+1][col1] - sums[row1][col2+1] + sums[row1][col1];
    }
};

图片引用自:灵茶山艾府

这道题的原理就在上面的图中,在NumMatrix中计算前缀和,然后在sumRegion中使用,要注意的是,sums要在函数外定义,如果在函数NumMatix中直接定义,则sumRegion无法使用。

相关推荐
Navigator_Z16 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
星恒随风1 天前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能
wy_hhxx1 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK2 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
饮水桶_T2 天前
HashMap笔记
开发语言·数据结构·笔记
风落青芜2 天前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z2 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah2 天前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
凌冰_2 天前
数据结构 - 渐进符号和递归的复杂度(二)
数据结构·算法·软件工程
Navigator_Z2 天前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode