原题链接在这里:https://leetcode.com/problems/range-sum-query-2d-mutable/

题目:

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
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10

题解:

用到了二维binary index tree.

Time Complexity: builder O(mnlogmn). update O(logmn). sumRange O(logmn). m = matrix.length. n = matrix[0].length.

Space : O(mn).

AC Java:

 public class NumMatrix {
int [][] bit;
int [][] matrix; public NumMatrix(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return;
}
int m = matrix.length;
int n = matrix[0].length;
this.bit = new int[m+1][n+1];
this.matrix = new int[m][n];
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
update(i, j, matrix[i][j]);
}
}
} public void update(int row, int col, int val) {
int diff = val - this.matrix[row][col];
this.matrix[row][col] = val;
for(int i = row+1; i<bit.length; i+=(i&-i)){
for(int j = col+1; j<bit[0].length; j+=(j&-j)){
this.bit[i][j] += diff;
}
}
} public int sumRegion(int row1, int col1, int row2, int col2) {
return getSum(row2+1, col2+1) - getSum(row1, col2+1) - getSum(row2+1, col1) + getSum(row1, col1);
} private int getSum(int row, int col){
int sum = 0;
for(int i = row; i>0; i-=(i&-i)){
for(int j = col; j>0; j-=(j&-j)){
sum += this.bit[i][j];
}
}
return sum;
}
} /**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* obj.update(row,col,val);
* int param_2 = obj.sumRegion(row1,col1,row2,col2);
*/

类似Range Sum Query - Mutable.

最新文章

  1. 数据库的快照隔离级别(Snapshot Isolation)
  2. sql基础语句
  3. spring所需包下载
  4. win7中protel99添加元件库
  5. JavaScript触摸与手势事件
  6. maven的pom报plugins却是的解决方法2
  7. c语言—临界资源管理
  8. 数据库修复工具 - DatabaseCompressor 之从9M到900K+
  9. 随手记今天跟的几个iOS项目代码的问题
  10. Webgis中关于Openlayers入门使用(一)安装及生成基本地图
  11. Markdown语法收录
  12. win7下,使用django运行django-admin.py无法创建网站
  13. Xamarin.Android多窗口传值【1】
  14. java学习笔记(八):继承、extends、super、this、final关键字
  15. socket、tcp、udp、http 的认识及区别
  16. golang GBK与UTF-8互转的例子
  17. 00004 - CentOS 7下安装pptp服务端
  18. 解决jsfl 弹出警告
  19. 团队作业(五)——旅游行业的手机App
  20. ****timeago.js插件:jquery实现几分钟前、几小时前、几天前等时间差显示效果的代码实例

热门文章

  1. Visual Studio 2019 离线安装方法
  2. C++基础(静态数据成员和静态成员函数)
  3. 二十二、DMA驱动
  4. AJAX一些注释掉的语句
  5. JS ES6中export和import详解
  6. 全栈项目|小书架|服务器开发-Koa全局路由实现
  7. PAT-1021 Deepest Root (25 分) 并查集判断成环和联通+求树的深度
  8. POJ 3233-Matrix Power Series( S = A + A^2 + A^3 + … + A^k 矩阵快速幂取模)
  9. java实现HTTP请求 HttpUtil
  10. 在论坛中出现的比较难的sql问题:12(递归问题2 拆分字符串)