当前位置:网站首页>leetcode-304:二维区域和检索 - 矩阵不可变
leetcode-304:二维区域和检索 - 矩阵不可变
2022-07-07 08:17:00 【菊头蝙蝠】
题目
给定一个二维矩阵 matrix,以下类型的多个请求:
- 计算其子矩形范围内元素的总和,该子矩阵的 左上角 为 (row1, col1) ,右下角 为 (row2, col2) 。
实现 NumMatrix 类:
- NumMatrix(int[][] matrix) 给定整数矩阵 matrix 进行初始化
- int sumRegion(int row1, int col1, int row2, int col2) 返回 左上角 (row1, col1) 、右下角 (row2, col2) 所描述的子矩阵的元素 总和 。
示例 1:
输入:
["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 (蓝色矩形框的元素总和)
解题
方法一:前缀和
preSums[i][j]表示左上角为(0,0),右下角索引为(i,j)的矩阵里的所有元素和
1、首先通过下述递推关系式计算出preSums[i][j]
S ( O , D ) = S ( O , C ) + S ( O , B ) − S ( O , A ) + D S(O,D)=S(O,C)+S(O,B)−S(O,A)+D S(O,D)=S(O,C)+S(O,B)−S(O,A)+D
2、根据已经计算出的preSums,可以得出想要计算的矩阵中所有元素之和
S ( A , D ) = S ( O , D ) − S ( O , E ) − S ( O , F ) + S ( O , G ) S(A,D)=S(O,D)−S(O,E)−S(O,F)+S(O,G) S(A,D)=S(O,D)−S(O,E)−S(O,F)+S(O,G)
class NumMatrix {
public:
vector<vector<int>> preSums;
NumMatrix(vector<vector<int>>& matrix) {
int m=matrix.size();
int n=matrix[0].size();
preSums.resize(m+1,vector<int>(n+1));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
preSums[i+1][j+1]=preSums[i+1][j]+preSums[i][j+1]-preSums[i][j]+matrix[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return preSums[row2+1][col2+1]-preSums[row1][col2+1]-preSums[row2+1][col1]+preSums[row1][col1];
}
};
边栏推荐
猜你喜欢

LeetCode 练习——113. 路径总和 II

Review of the losers in the postgraduate entrance examination

Appx code signing Guide

The variables or functions declared in the header file cannot be recognized after importing other people's projects and adding the header file

电表远程抄表拉合闸操作命令指令

ORM model -- associated fields, abstract model classes

STM32 Basics - memory mapping

Vs code specifies the extension installation location

柏拉图和他的三个弟子的故事:如何寻找幸福?如何寻找理想伴侣?

ISP、IAP、ICP、JTAG、SWD的编程特点
随机推荐
求方程ax^2+bx+c=0的根(C语言)
LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
MCU与MPU的区别
对存储过程进行加密和解密(SQL 2008/SQL 2012)
Slurm资源管理与作业调度系统安装配置
单片机(MCU)最强科普(万字总结,值得收藏)
OpenGL glLightfv 函数的应用以及光源的相关知识
5个chrome简单实用的日常开发功能详解,赶快解锁让你提升更多效率!
ArcGIS operation: batch modify attribute table
HDU-2196 树形DP学习笔记
移动端通过设置rem使页面内容及字体大小自动调整
【华为机试真题详解】高矮个子排队
ArcGIS operation: converting DWG data to SHP data
SQLyog数据库怎么取消自动保存更改
Appx代碼簽名指南
Google colab loads Google drive (Google drive is used in Google colab)
关于hzero-resource报错(groovy.lang.MissingPropertyException: No such property: weight for class)
Postman interface test V
Remote meter reading, switching on and off operation command