码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-11-16 19:38:55      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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.
 1 class NumArray {
 2 private:
 3     vector<int> acc;
 4     
 5 public:
 6     NumArray(vector<int> &nums) {
 7         acc.push_back(0);
 8         for (auto n : nums) {
 9             acc.push_back(acc.back() + n);
10         }
11     }
12 
13     int sumRange(int i, int j) {
14         return acc[j + 1] - acc[i];
15     }
16 };
17 
18 
19 // Your NumArray object will be instantiated and called as such:
20 // NumArray numArray(nums);
21 // numArray.sumRange(0, 1);
22 // 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).

技术分享
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.

 

 1 class NumMatrix {
 2 private:
 3     vector<vector<int>> acc;
 4 public:
 5     NumMatrix(vector<vector<int>> &matrix) {
 6         if (matrix.empty()) return;
 7         int n = matrix.size(), m = matrix[0].size();
 8         acc.resize(n + 1, vector<int>(m + 1));
 9         for (int i = 0; i <= n; ++i) acc[i][0] = 0;
10         for (int j = 0; j <= m; ++j) acc[0][j] = 0;
11         for (int i = 1; i <= n; ++i) {
12             for (int j = 1; j <= m; ++j) {
13                 acc[i][j] = acc[i][j-1] + acc[i-1][j] - acc[i-1][j-1] + matrix[i-1][j-1];
14             }
15         } 
16     }
17 
18     int sumRegion(int row1, int col1, int row2, int col2) {
19         return acc[row2+1][col2+1] - acc[row1][col2+1] - acc[row2+1][col1] + acc[row1][col1];
20     }
21 };
22 
23 
24 // Your NumMatrix object will be instantiated and called as such:
25 // NumMatrix numMatrix(matrix);
26 // numMatrix.sumRegion(0, 1, 2, 3);
27 // numMatrix.sumRegion(1, 2, 3, 4);

 

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

标签:

原文地址:http://www.cnblogs.com/easonliu/p/4969767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!