题目链接:https://leetcode.com/problems/range-sum-query-2d-immutable/
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:
思路:和Range Sum Query - Immutable一样,那一题是一维,这题是二维,但是方法都一样,都是存储一行到每一个位置之前数的和是多少。最后要求区间的时候就把前面的区间和去掉。
代码如下:
class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) { hash.resize(matrix.size()); for(int i = 0; i< matrix.size(); i++) { hash[i].resize(matrix[i].size()+1); hash[i][0] = 0; for(int j = 0; j < matrix[i].size(); j++) hash[i][j+1] = hash[i][j] + matrix[i][j]; } } int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; for(int i = row1; i <= row2; i++) sum += (hash[i][col2+1] - hash[i][col1]); return sum; } private: vector<vector<int>> hash; }; // 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);