当前位置:网站首页>剑指 Offer II 013. 二维子矩阵的和
剑指 Offer II 013. 二维子矩阵的和
2022-07-07 17:37: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 (蓝色矩形框的元素总和)
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/O4NDxx
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
java:
class NumMatrix {
public int[][] mat;
public NumMatrix(int[][] matrix) {
//给定二维数组,对二维数组进行初始化
// [[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]]]
this.mat = matrix;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int total = 0;
//求取给定下标的值
for(int i = row1;i <= row2 ; i++){
for(int j = col1;j<=col2;j++){
total += this.mat[i][j];
}
}
return total;
}
}
边栏推荐
猜你喜欢
Numpy——2. Shape of array
CMD command enters MySQL times service name or command error (fool teaching)
648. 单词替换
超分辨率技术在实时音视频领域的研究与实践
PV static creation and dynamic creation
ASP. Net kindergarten chain management system source code
Kirin Xin'an with heterogeneous integration cloud financial information and innovation solutions appeared at the 15th Hunan Financial Technology Exchange Conference
Numpy——axis
RESTAPI 版本控制策略【eolink 翻译】
Download from MySQL official website: mysql8 for Linux X Version (Graphic explanation)
随机推荐
L1-023 output gplt (Lua)
索引总结(突击版本)
UCloud是基础云计算服务提供商
L1-027 rental (Lua)
L1-028 judging prime number (Lua)
Empowering smart power construction | Kirin Xin'an high availability cluster management system to ensure the continuity of users' key businesses
# 欢迎使用Markdown编辑器
What does "true" mean
Key points of anti reptile: identifying reptiles
【Confluence】JVM内存调整
Introduction to bit operation
解决rosdep的报错问题
Download from MySQL official website: mysql8 for Linux X Version (Graphic explanation)
Unable to link the remote redis server (solution 100%
L1-019 who falls first (Lua)
How to open an account for stock speculation? Excuse me, is it safe to open a stock account by mobile phone?
2022.07.04
5billion, another master fund was born in Fujian
LeetCode1051(C#)
Former richest man, addicted to farming