当前位置:网站首页>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];
}
};
边栏推荐
猜你喜欢

JMeter about setting thread group and time

Fiddler break point

ISP、IAP、ICP、JTAG、SWD的编程特点

Programming features of ISP, IAP, ICP, JTAG and SWD

555电路详解

Word自动生成目录的方法

Weekly recommended short videos: what are the functions of L2 that we often use in daily life?

P2788 数学1(math1)- 加减算式

Postman interface test II

The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
随机推荐
Use of JSON extractor originals in JMeter
Why is the reflection efficiency low?
【acwing】786. Number k
@Transcation的配置,使用,原理注意事项:
C logging method
Fiddler break point
【STM32】STM32烧录程序后SWD无法识别器件的问题解决方法
Can I open a stock trading account online? Is it safe
【华为机试真题详解】高矮个子排队
Guid primary key
Socket通信原理和实践
2022.7.6DAY598
Advanced function learning in ES6
Serial communication relay Modbus communication host computer debugging software tool project development case
STM32 product introduction
JMeter installation
ORM -- query type, association query
. Net configuration system
成为优秀的TS体操高手 之 TS 类型体操前置知识储备
The method of word automatically generating directory