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), 1sumRange (2, 5), -1sumrange (0, 5), 3
Note:
- Assume that the array does is not a change.
- There is many calls to sumrange function.
1 classNumarray {2 Private:3vector<int>acc;4 5 Public:6Numarray (vector<int> &nums) {7Acc.push_back (0);8 for(Auto n:nums) {9Acc.push_back (Acc.back () +n);Ten } One } A - intSumrange (intIintj) { - returnAcc[j +1] -Acc[i]; the } - }; - - + //Your Numarray object would be instantiated and called as such: - //Numarray Numarray (nums); + //numarray.sumrange (0, 1); A //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 it upper left corner ( row1, Col1) and lower right corner ( row2, Col2).
The above rectangle (with the red border) are defined by (row1, col1) = (2, 1) and (Row2, col2) = (4, 3), which contains Su m = 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), 8sumRegion (1, 1, 2, 2), 11sumRegion (1, 2, 2, 4), 12
Note:
- Assume that the matrix does not a change.
- There is many calls to sumregion function.
- Assume that row1≤ row2 and Col1≤ Col2.
1 classNummatrix {2 Private:3vector<vector<int>>acc;4 Public:5Nummatrix (vector<vector<int>> &matrix) {6 if(Matrix.empty ())return;7 intn = matrix.size (), M = matrix[0].size ();8Acc.resize (n +1, vector<int> (M +1));9 for(inti =0; I <= N; ++i) acc[i][0] =0;Ten for(intj =0; J <= M; ++J) acc[0][J] =0; One for(inti =1; I <= N; ++i) { A for(intj =1; J <= M; ++j) { -ACC[I][J] = acc[i][j-1] + acc[i-1][J]-acc[i-1][j-1] + matrix[i-1][j-1]; - } the } - } - - intSumregion (intRow1,intCol1,intRow2,intcol2) { + returnacc[row2+1][col2+1]-acc[row1][col2+1]-acc[row2+1][COL1] +Acc[row1][col1]; - } + }; A at - //Your Nummatrix object would be instantiated and called as such: - //Nummatrix Nummatrix (matrix); - //nummatrix.sumregion (0, 1, 2, 3); - //nummatrix.sumregion (1, 2, 3, 4);
[Leetcode] Range sum query-immutable & range sum Query 2d-immutable