矩阵 - 二维区域和检索 - 矩阵不可变,leetcode 304
Posted GoldenaArcher
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了矩阵 - 二维区域和检索 - 矩阵不可变,leetcode 304相关的知识,希望对你有一定的参考价值。
矩阵 - 二维区域和检索 - 矩阵不可变,leetcode 304
github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。
题目地址:
题目
如下:
Given a 2D matrix
matrix
, handle multiple queries of the following type:
Calculate the sum of the elements of
matrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.
Implement the NumMatrix class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrixmatrix
.
int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements ofmatrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.
解题思路
这题主要还是有点考对语言的了解,首先就是 javascript 的 this
指向,首先看一下原题给的核心代码:
/**
* @param number[][] matrix
*/
var NumMatrix = function (matrix) ;
/**
* @param number row1
* @param number col1
* @param number row2
* @param number col2
* @return number
*/
NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) ;
/**
* Your NumMatrix object will be instantiated and called as such:
* var obj = new NumMatrix(matrix)
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
*/
所以依然是怎么在函数中获取 matrix
,除了语言这一关之外,其他倒也没有什么特别难得。
题目中所提供的 row1
, col1
, row2
, col2
就是计算
(
r
o
w
2
−
r
o
w
1
)
×
(
c
o
l
2
−
c
o
l
1
)
(row2 - row1) \\times (col2 - col1)
(row2−row1)×(col2−col1) 的和。也就是获取出现在 row1
到 row2
,col1
到 col2
这一个子矩阵中出现所有数字之和。
以红色区域来说,调用的方式为 numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
,实现的过程需要获取 [[2, 1], ..., [2, 3], ..., [4, 1], ..., [4,3]]
这个子阵中出现所有数字之和。
使用 JavaScript 解题
/**
* @param number[][] matrix
*/
var NumMatrix = function (matrix)
this.matrix = matrix;
;
/**
* @param number row1
* @param number col1
* @param number row2
* @param number col2
* @return number
*/
NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2)
let sum = 0;
for (let i = row1; i <= row2; i++)
for (let j = col1; j <= col2; j++)
sum += this.matrix[i][j];
return sum;
;
/**
* Your NumMatrix object will be instantiated and called as such:
* var obj = new NumMatrix(matrix)
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
*/
以上是关于矩阵 - 二维区域和检索 - 矩阵不可变,leetcode 304的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 0304. 二维区域和检索 - 矩阵不可变
Leetcode——区域和检索 - 数组不可变 / 二维区域和检索 - 矩阵不可变 (前缀和)