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

Range Sum Query 2D
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
Note:
The matrix is only modifiable by the update function.
You may assume the number of calls to update and sumRegion function is distributed evenly.
You may assume that row1 ≤ row2 and col1 ≤ col2.

参考:https://leetcode.com/discuss/72685/share-my-java-2-d-binary-indexed-tree-solution

Build binary indexed tree takes :   O(mn*logm*logn)   time, both update() and getSum() take:      O(logm*logn)   time. The arr[][] is used to keep a backup of the matrix[][] so that we know the difference of the updated element and use that to update the binary indexed tree. The idea of calculating sumRegion() is the same as in Range Sum Query 2D - Immutable.

Summary of Binary Indexed Tree:

Binary Index Tree参见:https://www.youtube.com/watch?v=CWDQJGaN1gY

Compare Segment Tree vs Binary Indexed Tree

Segment Tree:

      Time: O(N)build, O(logN)search, O(logN) update,   space: O(NlogN)

Binary Indexed Tree:

      Time: O(NlogN)build, O(logN) search, O(logN) update,   space: O(N)

The advantage of Binary Indexed Tree over Segment Tree are:

require less space and very easy to implement

 public class Solution {
int m, n;
int[][] arr; // stores matrix[][]
int[][] BITree; // 2-D binary indexed tree public Solution(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return;
} m = matrix.length;
n = matrix[0].length; arr = new int[m][n];
BITree = new int[m + 1][n + 1]; for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
update(i, j, matrix[i][j]); // init BITree[][] }
}
} public void update(int i, int j, int val) {
int diff = val - arr[i][j]; // get the diff
arr[i][j] = val; // update arr[][] i++; j++;
for (int x=i; x<=m; x+=x&(-x)) {
for (int y=j; y<=n; y+=y&(-y)) {
BITree[x][y] += diff;
}
}
} int getSum(int i, int j) {
int sum = 0; i++; j++;
for (int x=i; x>0; x-=x&(-x)) {
for (int y=j; y>0; y-=y&(-y)) {
sum += BITree[x][y];
}
}
return sum;
} public int sumRegion(int i1, int j1, int i2, int j2) {
return getSum(i2, j2) - getSum(i1-1, j2) - getSum(i2, j1-1) + getSum(i1-1, j1-1);
}

Introduction from GeeksforGeeks:

We have an array arr[0 . . . n-1]. We should be able to
1 Find the sum of first i elements.
Update value of a specified element of the array arr[i] = x where 0 <= i <= n-1.

simple solution is to run a loop from 0 to i-1 and calculate sum of elements. To update a value, simply do arr[i] = x. The first operation takes O(n) time and second operation takes O(1) time. Another simple solution is to create another array and store sum from start to i at the i’th index in this array. Sum of a given range can now be calculated in O(1) time, but update operation takes O(n) time now. This works well if the number of query operations are large and very few updates.

Can we perform both the operations in O(log n) time once given the array? 
One Efficient Solution is to use Segment Tree that does both operations in O(Logn) time.

Using Binary Indexed Tree, we can do both tasks in O(Logn) time. The advantages of Binary Indexed Tree over Segment are, requires less space and very easy to implement..

Representation
Binary Indexed Tree is represented as an array. Let the array be BITree[]. Each node of Binary Indexed Tree stores sum of some elements of given array. Size of Binary Indexed Tree is equal to n where n is size of input array. In the below code, we have used size as n+1 for ease of implementation.(index 0 is a dummy node)

Construction
We construct the Binary Indexed Tree by first initializing all values in BITree[] as 0. Then we call update() operation for all indexes to store actual sums, update is discussed below.

Operations

getSum(index): Returns sum of arr[0..index]
// Returns sum of arr[0..index] using BITree[0..n]. It assumes that
// BITree[] is constructed for given array arr[0..n-1]
1) Initialize sum as 0 and index as index+1.
2) Do following while index is greater than 0.
...a) Add BITree[index] to sum
...b) Go to parent of BITree[index]. Parent can be obtained by removing
the last set bit from index, i.e., index = index - (index & (-index))
3) Return sum.


The above diagram demonstrates working of getSum(). Following are some important observations.

Node at index 0 is a dummy node.

A node at index y is parent of a node at index x, iff y can be obtained by removing last set bit from binary representation of x.

A child x of a node y stores sum of elements from of y(exclusive y) and of x(inclusive x).

update(index, val): Updates BIT for operation arr[index] += val
// Note that arr[] is not changed here. It changes
// only BI Tree for the already made change in arr[].
1) Initialize index as index+1.
2) Do following while index is smaller than or equal to n.
...a) Add value to BITree[index]
...b) Go to next node of BITree[index]. Next node can be obtained by i.e., index = index + (index & (-index))

Leetcode: Range Sum Query 2D - Mutable && Summary: Binary Indexed Tree的更多相关文章

  1. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  2. LeetCode Range Sum Query 2D - Mutable

    原题链接在这里:https://leetcode.com/problems/range-sum-query-2d-mutable/ 题目: Given a 2D matrix matrix, find ...

  3. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  4. Range Sum Query 2D - Mutable & Immutable

    Range Sum Query 2D - Mutable Given a 2D matrix matrix, find the sum of the elements inside the recta ...

  5. [Locked] Range Sum Query 2D - Mutable

    Range Sum Query 2D - Mutable Given a 2D matrix matrix, find the sum of the elements inside the recta ...

  6. LeetCode 308. Range Sum Query 2D - Mutable

    原题链接在这里:https://leetcode.com/problems/range-sum-query-2d-mutable/ 题目: Given a 2D matrix matrix, find ...

  7. 308. Range Sum Query 2D - Mutable

    题目: Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper ...

  8. [LeetCode] Range Sum Query 2D - Immutable

    Very similar to Range Sum Query - Immutable, but we now need to compute a 2d accunulated-sum. In fac ...

  9. [Swift]LeetCode308. 二维区域和检索 - 可变 $ Range Sum Query 2D - Mutable

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

随机推荐

  1. vector 初始化所有方法

    简介:vector可用于代替C中的数组,或者MFC中的CArray,从许多说明文档或者网上评论,一般一致认为应该多用vector,因为它的效率更高,而且具备很好的异常安全性.而且vector是STL推 ...

  2. ssi服务器端指令

    SSI使用详解 你是否曾经或正在为如何能够在最短的时间内完成对一个包含上千个页面的网站的修改而苦恼?那么可以看一下本文的介绍,或许能够对你有所帮助.什么是SSI?SSI是英文Server Side I ...

  3. membership 在web.config中配置信息

    <?xml version="1.0" encoding="utf-8"?><configuration> <configSect ...

  4. Git and Xcode

    1.web site "New Repository" 2.为本地 git 管理的项目添加 Repository $ cd ~/ProjectName$ git remote ad ...

  5. git-svn

    sudo apt-get install git-svn svn作为一个优秀源码版本的管理工具,可以适合绝大多数项目.但是因为它的采用中心化管理,不可避免的存在本地代码的备份和版本管理问题.也就是说对 ...

  6. docker ubuntu

    DOCKER教程 注意事项 1.官方申明docker还是在开发完善中,不建议在运营的产品中使用它,但是现在离正式版越来越接近了,请关注我们的博客http://blog.docker.io/2013/0 ...

  7. 读书笔记——《图解TCP/IP》(3/4)

    经典摘抄 第五章 IP协议相关技术 1.DNS可以将网址自动转换为具体的IP地址. 2.主机识别码的识别方式:为每台计算机赋以唯一的主机名,在进行网络通信时,可以直接使用主机名称而无需输入一大长串的I ...

  8. Java中对象构造

    构造函数 作用:在构造对象的同时初始化对象.java强制要求对象 诞生同时被初始化,保证数据安全. 调用过程和机制:①申请内存,②执行构造函数的函数体,③返回对象的引用. 特点:与类同名,无返回类型, ...

  9. Selenium2学习-001-Selenium2 WebUI自动化Java开发 Windows 环境配置

    此文主要介绍 Selenium2 WebUI自动化Java开发 Windows 环境配置,供各位亲们参考,若有不足之处,敬请各位大神指正,非常感谢! 所需软件列表如下所示: 所属分类 具体名称 备注 ...

  10. C#中派生类调用基类构造函数用法分析

    这里的默认构造函数是指在没有编写构造函数的情况下系统默认的无参构造函数 1.当基类中没有自己编写构造函数时,派生类默认的调用基类的默认构造函数例如: ? 1 2 3 4 5 6 7 8 9 10 11 ...