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

[LeetCode] Range Sum Query 2D - Immutable

2015-11-12 22:00 330 查看
Very similar to Range Sum Query - Immutable, but we now need to compute a 2d accunulated-sum. In fact, if you work in computer vision, you may know a name for such an array --- Integral Image.

To solve this problem, Stefan has already posted a very elegant solution.

The code is copied here.

class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
accu = matrix;
for (int i = 0; i < matrix.size(); i++)
for (int j = 0; j < matrix[0].size(); j++)
accu[i][j] += a(i-1, j) + a(i, j-1) - a(i-1, j-1);
}

int sumRegion(int row1, int col1, int row2, int col2) {
return a(row2, col2) - a(row1-1, col2) - a(row2, col1-1) + a(row1-1, col1-1);
}
private:
vector<vector<int>> accu;
int a(int i, int j) {
return i >= 0 && j >= 0 ? accu[i][j] : 0;
}
};

// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: