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

lintcode--平面范围求和-不可变矩阵(leetcode--Range Sum Query 2D)

2017-12-21 17:33 483 查看
题目描述:

给一 二维矩阵,计算由左上角 (row1, col1) 和右下角 (row2, col2) 划定的矩形内元素和.

注意事项:

1.你可以假设矩阵不变

2.对函数 sumRegion 的调用次数有很多次

3.你可以假设 row1 ≤ row2 并且 col1 ≤ col2

样例:

给出矩阵

[

[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

思路讲解:

首先我们看一下这个注意事项中的一、二项,说明如果我们多次调用,所以这就导致我们多次进行求和,进而导致时间超时,思考了很久,发现一个很好的方法就是我们可以提前求好 ,什么时候需要的时候 直接调用就好了,但是如果我们提前把所有的都算好,空间复杂度太高可能会导致存储不够,所以我们想到了可以直接用每一个位置到起始位置00的和,到时候我们可以通过对其进行加减得出自己想要的那一部分的和。具体思路就是这样。

详细代码:

class NumMatrix {
public:
/*
* @param matrix: a 2D matrix
*/

private:
int row;
int col;
vector<vector<int>> sums;
public:
NumMatrix(vector<vector<int>> matrix) {
// do intialization if necessary
row = matrix.size();
col = row>0 ? matrix[0].size() : 0;
sums = vector<vector<int>>(row+1, vector<int>(col+1, 0));
for(int i=1; i<=row; i++) {
for(int j=1; j<=col; j++) {
sums[i][j] = matrix[i-1][j-1] + sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] ;
}
}
}

/*
* @param row1: An integer
* @param col1: An integer
* @param row2: An integer
* @param col2: An integer
* @return: An integer
*/
int sumRegion(int row1, int col1, int row2, int col2) {
// write your code here
return sums[row2+1][col2+1] - sums[row2+1][col1] - sums[row1][col2+1] + sums[row1][col1];
}
};

/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: