[LeetCode] Range Sum Query - Immutable & Range Sum Query 2D - Immutable

时间:2021-03-17 14:29:58

Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.
 class NumArray {
private:
vector<int> acc; public:
NumArray(vector<int> &nums) {
acc.push_back();
for (auto n : nums) {
acc.push_back(acc.back() + n);
}
} int sumRange(int i, int j) {
return acc[j + ] - acc[i];
}
}; // Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);

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).

[LeetCode] Range Sum Query - Immutable & Range Sum Query 2D - Immutable
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:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.
 class NumMatrix {
private:
vector<vector<int>> acc;
public:
NumMatrix(vector<vector<int>> &matrix) {
if (matrix.empty()) return;
int n = matrix.size(), m = matrix[].size();
acc.resize(n + , vector<int>(m + ));
for (int i = ; i <= n; ++i) acc[i][] = ;
for (int j = ; j <= m; ++j) acc[][j] = ;
for (int i = ; i <= n; ++i) {
for (int j = ; j <= m; ++j) {
acc[i][j] = acc[i][j-] + acc[i-][j] - acc[i-][j-] + matrix[i-][j-];
}
}
} int sumRegion(int row1, int col1, int row2, int col2) {
return acc[row2+][col2+] - acc[row1][col2+] - acc[row2+][col1] + acc[row1][col1];
}
}; // 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);