[leetcode] 303. Range Sum Query && 304. Range Sum Query 2D - Immutable

时间:2022-06-23 20:45:28

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.

Subscribe to see which companies asked this question

 1 class NumArray 
 2 {
 3 public:
 4     NumArray(vector<int> &nums) 
 5     {
 6         sums.push_back(0);
 7         for (int i = 0; i < nums.size(); i++)
 8         {
 9             sums.push_back(sums[i] + nums[i]);
10         }
11     }
12 
13     int sumRange(int i, int j) 
14     {
15         return sums[j + 1] - sums[i];    
16     }
17 private:
18     vector<int> sums;
19 };

 

 

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] 303. Range Sum Query && 304. 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.

 

 

Subscribe to see which companies asked this question

 1 class NumMatrix 
 2 {
 3 public:
 4     NumMatrix(vector<vector<int>> &matrix) 
 5     {
 6         unsigned int nrow = matrix.size();
 7         if (nrow == 0)
 8             return;
 9         unsigned int ncol = matrix[0].size();
10         
11         for (int i = 0; i <= nrow; i++)
12         {
13             vector<int> row(ncol + 1, 0);
14             matsum.push_back(row);
15         }
16         
17         for (int i = 0; i < nrow; i++)
18         {
19             for (int j = 0; j < ncol; j++)
20             {
21                 matsum[i + 1][j + 1] = matsum[i][j + 1] + matsum[i + 1][j] - matsum[i][j] + matrix[i][j];
22             }
23         }
24     }
25 
26     int sumRegion(int row1, int col1, int row2, int col2) 
27     {
28         return matsum[row2 + 1][col2 + 1] - matsum[row2 + 1][col1] - matsum[row1][col2 + 1] + matsum[row1][col1];
29     }
30 private:
31     vector<vector<int> > matsum;
32 };