您的位置:首页 > 产品设计 > UI/UE

LeetCode 304 Range Sum Query 2D - Immutable(范围求和2D - 不可变)

2016-06-29 15:33 555 查看

翻译

给定一个2D矩阵matrix,找出其中以左上角(row1,col1)和右下角(row2,col2)定义的矩形边界的元素的和。(译者注:包括边界)



以上矩形 范围内的元素和为8。

例如,

给定 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]

]

sumRegion(2, 1, 4, 3) -> 8

sumRegion(1, 1, 2, 2) -> 11

sumRegion(1, 2, 2, 4) -> 12

备注:

你可以假定矩阵不会变化。

此处会有很多次对于sumRegion函数的调用。

你可以假定 row1 ≤ row2 以及 col1 ≤ col2 。

原文

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).



The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given 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]

]

sumRegion(2, 1, 4, 3) -> 8

sumRegion(1, 1, 2, 2) -> 11

sumRegion(1, 2, 2, 4) -> 12

Note:

You may assume that the matrix does not change.

There are many calls to sumRegion function.

You may assume that row1 ≤ row2 and col1 ≤ col2.

分析

可以参考相关的上一道题,其实方法是类似的。

LeetCode 307 Range Sum Query - Mutable(范围和查询-可变)

原始方法

我们首先也还是用原始方法,但这次并不能通过了,原因大家都懂,太慢了。

class NumMatrix {
private:
vector<vector<int>> matrixV;
public:
NumMatrix(vector<vector<int>> &matrix) {
matrixV = matrix;
}

int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for (int i = row1; i <= row2; i++) {
for (int j = col1; j <= col2; j++) {
sum += matrixV[i][j];
}
}
return sum;
}
};


然后企图更具上一题的开方划分的方式来解决,努力了很长时间还是无果……

哎,还是要多学些算法,应该遇到问题就能知道哪些方法注定无果,不然一直尝试太累了………………再也不想通过for循环来解决问题了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: