304. Range Sum Query 2D - Immutable
https://leetcode.com/problems/range-sum-query-2d-immutable/description/
Thoughts
Code
class NumMatrix {
public:
vector<vector<int>> presum;
NumMatrix(vector<vector<int>>& matrix) {
const int M = matrix.size(), N = M == 0 ? 0 : matrix[0].size();
presum.resize(M, vector<int>(N, 0));
for (int j = 0; j < N; ++j) {
for (int i = 0, s = 0; i < M; ++i) {
presum[i][j] = matrix[i][j];
if (i > 0) presum[i][j] += presum[i - 1][j];
if (j > 0) presum[i][j] += presum[i][j - 1];
if (i > 0 && j > 0) presum[i][j] -= presum[i - 1][j - 1];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
const auto up = col1 > 0 ? presum[row2][col1 - 1] : 0, left = row1 > 0 ? presum[row1 - 1][col2] : 0, overlap = col1 > 0 && row1 > 0 ? presum[row1 - 1][col1 - 1] : 0;
return presum[row2][col2] - up - left + overlap;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/Analysis
Last updated