Leetcode 304 - Range Sum Query 2D - Immutable
https://kennyzhuang.gitbooks.io/leetcode-lock/content/308_range_sum_query_2d_-_mutable.html
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
http://shibaili.blogspot.com/2018/11/308range-sum-query-2d-mutable.html
X.
https://yeqiuquan.blogspot.com/2017/06/308-range-sum-query-2d-mutable.html
We use int[][] colSum to store the prefix sum of each column.
colSum[i][j] denotes the sum of first i elements in column j.
To update an element, we find the corresponding column and update all the prefix sums that rely on this element.
X. 2D BIT
https://zhuhan0.blogspot.com/2017/09/leetcode-308-range-sum-query-2d-mutable.html
https://zhuhan0.blogspot.com/2017/09/leetcode-308-range-sum-query-2d-mutable.html
https://www.cnblogs.com/yrbbest/p/5058571.html
http://bookshadow.com/weblog/2015/11/18/leetcode-range-sum-query-mutable/
class NumArray(object): def __init__(self, nums): self.nums = nums self.size = size = len(nums) h = int(math.ceil(math.log(size, 2))) if size else 0 maxSize = 2 ** (h + 1) - 1 self.st = [0] * maxSize if size: self.initST(0, size - 1, 0) def update(self, i, val): if i < 0 or i >= self.size: return diff = val - self.nums[i] self.nums[i] = val self.updateST(0, self.size - 1, i, diff, 0) def sumRange(self, i, j): """ if i < 0 or j < 0 or i >= self.size or j >= self.size: return 0 return self.sumRangeST(0, self.size - 1, i, j, 0) def initST(self, ss, se, si): if ss == se: self.st[si] = self.nums[ss] else: mid = (ss + se) / 2 self.st[si] = self.initST(ss, mid, si * 2 + 1) + \ self.initST(mid + 1, se, si * 2 + 2) return self.st[si] def updateST(self, ss, se, i, diff, si): if i < ss or i > se: return self.st[si] += diff if ss != se: mid = (ss + se) / 2 self.updateST(ss, mid, i, diff, si * 2 + 1) self.updateST(mid + 1, se, i, diff, si * 2 + 2) def sumRangeST(self, ss, se, qs, qe, si): if qs <= ss and qe >= se: return self.st[si] if se < qs or ss > qe: return 0 mid = (ss + se) / 2 return self.sumRangeST(ss, mid, qs, qe, si * 2 + 1) + \ self.sumRangeST(mid + 1, se, qs, qe, si * 2 + 2) 解法II:树状数组(Binary Indexed Tree / Fenwick Tree)
class NumArray(object): def __init__(self, nums): self.sums = [0] * (len(nums) + 1) self.nums = nums self.n = len(nums) for i in xrange(len(nums)): self.add(i + 1,nums[i]) def add(self,x,val): while x <= self.n: self.sums[x] += val x += self.lowbit(x) def lowbit(self,x): return x & -x def sum(self,x): res = 0 while x > 0: res += self.sums[x] x -= self.lowbit(x) return res def update(self, i, val): self.add(i + 1, val - self.nums[i]) self.nums[i] = val def sumRange(self, i, j): if not self.nums: return 0 return self.sum(j+1) - self.sum(i)
X.
https://leetcode.com/discuss/70948/15ms-easy-to-understand-java-solution
http://www.1point3acres.com/bbs/thread-210173-1-1.html
其实后来发现我给的解法 好像就是quad tree。
对于quad tree每一个region,存总的sum, 和所有row的 和 所有column 的sum。. visit 1point3acres.com for more.
递归过程t(n) = t(n/2) +O(n) 因为只有一个quadrant 需要 recursive call, 其他的可以直接根据region 存的值算出来 所以是o(n)
https://kennyzhuang.gitbooks.io/leetcode-lock/content/308_range_sum_query_2d_-_mutable.html
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
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.
read heavy - 那就正常写,矩阵里面直接存cumulative sum. 读是O(1), 写是O(m * n)
write heavy - bit, 读写都是O(log m * log n)
X.
Idea: it should come out some way to store the computed results of sums and get region sum based on the pre-computed results. “Range Sum” is a good idea in this case, because every element in the matrix stores the sum of all previous elements in this row and it can get the range sum by difference of end element and previous element of start point.
We use int[][] colSum to store the prefix sum of each column.
colSum[i][j] denotes the sum of first i elements in column j.
To update an element, we find the corresponding column and update all the prefix sums that rely on this element.
public int[][] colSum; public int[][] matrix; public NumMatrix(int[][] matrix) { this.matrix = matrix; if (matrix == null || matrix.length == 0) { return; } if (matrix[0] == null || matrix[0].length == 0) { return; } int m = matrix.length; int n = matrix[0].length; colSum = new int[m + 1][n]; for (int i = 1; i <= m; i++) { for (int j = 0; j < n; j++) { colSum[i][j] = colSum[i - 1][j] + matrix[i - 1][j]; } } } public void update(int row, int col, int val) { for (int i = row + 1; i < colSum.length; i++) { colSum[i][col] = colSum[i][col] - matrix[row][col] + val; } matrix[row][col] = val; } public int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; for (int j = col1; j <= col2; j++) { sum += colSum[row2 + 1][j] - colSum[row1][j]; } return sum; }
X. 2D BIT
https://zhuhan0.blogspot.com/2017/09/leetcode-308-range-sum-query-2d-mutable.html
https://zhuhan0.blogspot.com/2017/09/leetcode-308-range-sum-query-2d-mutable.html
Say height = h and width = w.
- Constructor: hw logh logw.
- update(): logh logw.
- sumRegion(): logh logw.
private int[][] matrix; private int[][] tree; private int height; private int width; public NumMatrix(int[][] matrix) { height = matrix.length; if (height == 0) { return; } width = matrix[0].length; this.matrix = new int[height][width]; tree = new int[height + 1][width + 1]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { update(i, j, matrix[i][j]); } } } public void update(int row, int col, int val) { int diff = val - matrix[row][col]; matrix[row][col] = val; for (int i = row + 1; i <= height; i += (i & -i)) { for (int j = col + 1; j <= width; j += (j & -j)) { tree[i][j] += diff; } } } public int sumRegion(int row1, int col1, int row2, int col2) { return sum(row2, col2) - sum(row1 - 1, col2) - sum(row2, col1 - 1) + sum(row1 - 1, col1 - 1); } private int sum(int row, int col) { int sum = 0; for (int i = row + 1; i > 0; i -= (i & -i)) { for (int j = col + 1; j > 0; j -= (j & -j)) { sum += tree[i][j]; } } return sum; }
int[][] tree;
int[][] nums;
int m;
int n;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return;
m = matrix.length;
n = matrix[0].length;
tree = new int[m+1][n+1];
nums = 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) {
if (m == 0 || n == 0) return;
int delta = val - nums[row][col];
nums[row][col] = val;
for (int i = row + 1; i <= m; i += i & (-i)) {
for (int j = col + 1; j <= n; j += j & (-j)) {
tree[i][j] += delta;
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
if (m == 0 || n == 0) return 0;
return sum(row2+1, col2+1) + sum(row1, col1) - sum(row1, col2+1) - sum(row2+1, col1);
}
public int sum(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 += tree[i][j];
}
}
return sum;
}
https://www.cnblogs.com/yrbbest/p/5058571.html
http://bookshadow.com/weblog/2015/11/18/leetcode-range-sum-query-mutable/
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Note:
- The array is only modifiable by the update function.
- You may assume the number of calls to update and sumRange function is distributed evenly.
class NumArray(object): def __init__(self, nums): self.nums = nums self.size = size = len(nums) h = int(math.ceil(math.log(size, 2))) if size else 0 maxSize = 2 ** (h + 1) - 1 self.st = [0] * maxSize if size: self.initST(0, size - 1, 0) def update(self, i, val): if i < 0 or i >= self.size: return diff = val - self.nums[i] self.nums[i] = val self.updateST(0, self.size - 1, i, diff, 0) def sumRange(self, i, j): """ if i < 0 or j < 0 or i >= self.size or j >= self.size: return 0 return self.sumRangeST(0, self.size - 1, i, j, 0) def initST(self, ss, se, si): if ss == se: self.st[si] = self.nums[ss] else: mid = (ss + se) / 2 self.st[si] = self.initST(ss, mid, si * 2 + 1) + \ self.initST(mid + 1, se, si * 2 + 2) return self.st[si] def updateST(self, ss, se, i, diff, si): if i < ss or i > se: return self.st[si] += diff if ss != se: mid = (ss + se) / 2 self.updateST(ss, mid, i, diff, si * 2 + 1) self.updateST(mid + 1, se, i, diff, si * 2 + 2) def sumRangeST(self, ss, se, qs, qe, si): if qs <= ss and qe >= se: return self.st[si] if se < qs or ss > qe: return 0 mid = (ss + se) / 2 return self.sumRangeST(ss, mid, qs, qe, si * 2 + 1) + \ self.sumRangeST(mid + 1, se, qs, qe, si * 2 + 2) 解法II:树状数组(Binary Indexed Tree / Fenwick Tree)
class NumArray(object): def __init__(self, nums): self.sums = [0] * (len(nums) + 1) self.nums = nums self.n = len(nums) for i in xrange(len(nums)): self.add(i + 1,nums[i]) def add(self,x,val): while x <= self.n: self.sums[x] += val x += self.lowbit(x) def lowbit(self,x): return x & -x def sum(self,x): res = 0 while x > 0: res += self.sums[x] x -= self.lowbit(x) return res def update(self, i, val): self.add(i + 1, val - self.nums[i]) self.nums[i] = val def sumRange(self, i, j): if not self.nums: return 0 return self.sum(j+1) - self.sum(i)
X.
https://leetcode.com/discuss/70948/15ms-easy-to-understand-java-solution
We use colSums[j][i] = the sum of ( matrix[0][j], matrix[1][j], matrix[2][j],......,matrix[i - 1][j] ).
private int[][] colSums;
private int[][] matrix;
public NumMatrix(int[][] matrix) {
if( matrix == null
|| matrix.length == 0
|| matrix[0].length == 0 ){
return;
}
this.matrix = matrix;
int m = matrix.length;
int n = matrix[0].length;
colSums = new int[n][m + 1];
for(int i = 0; i < n; i++){
for(int j = 1; j <= m; j++){
colSums[i][j] = colSums[i][j - 1] + matrix[j - 1][i];
}
}
}
//time complexity for the worst case scenario: O(m)
public void update(int row, int col, int val) {
for(int i = row + 1; i < colSums[0].length; i++){
colSums[col][i] = colSums[col][i] - matrix[row][col] + val;
}
matrix[row][col] = val;
}
//time complexity for the worst case scenario: O(n)
public int sumRegion(int row1, int col1, int row2, int col2) {
int ret = 0;
for(int j = col1; j <= col2; j++){
ret += colSums[j][row2 + 1] - colSums[j][row1];
}
return ret;
}
https://discuss.leetcode.com/topic/30250/15ms-easy-to-understand-java-solution/12
This can be improved to O(1) space. I changed it to row sum version. BTW I think this solution is better than the BIT version since it's quite hard to give a BIT solution during an interview (unless you have seen BIT before).
// O(1) space
int[][] mMatrix = null;
int m = 0;
int n = 0;
public NumMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
mMatrix = matrix;
m = matrix.length;
n = matrix[0].length;
// rowSums[i][j] = rowSums[i][0] + rowSums[i][1] + ... + rowSums[i][j]
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
matrix[i][j] = matrix[i][j] + matrix[i][j - 1];
}
}
}
// O(n)
public void update(int row, int col, int val) {
// handle col = 0 differently
int originalValue = col == 0 ? mMatrix[row][0] : mMatrix[row][col] - mMatrix[row][col - 1];
int diff = val - originalValue;
for (int j = col; j < n; j++) {
mMatrix[row][j] += diff;
}
}
// O(m)
public int sumRegion(int row1, int col1, int row2, int col2) {
int result = 0;
for (int i = row1; i <= row2; i++) {
// handle col = 0 differently
result += col1 == 0 ? mMatrix[i][col2] : mMatrix[i][col2] - mMatrix[i][col1 - 1];
}
return result;
}
https://kennyzhuang.gitbooks.io/leetcode-lock/content/308_range_sum_query_2d_-_mutable.htmlpublic class NumMatrix {
int[][] tree;
int[][] nums;
int m;
int n;
public NumMatrix(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) return;
m = matrix.length;
n = matrix[0].length;
tree = new int[m+1][n+1];
nums = 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) {
if (m == 0 || n == 0) return;
int delta = val - nums[row][col];
nums[row][col] = val;
for (int i = row + 1; i <= m; i += i & (-i)) {
for (int j = col + 1; j <= n; j += j & (-j)) {
tree[i][j] += delta;
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
if (m == 0 || n == 0) return 0;
return sum(row2+1, col2+1) + sum(row1, col1) - sum(row1, col2+1) - sum(row2+1, col1);
}
public int sum(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 += tree[i][j];
}
}
return sum;
}
}
http://www.1point3acres.com/bbs/thread-210173-1-1.html
其实后来发现我给的解法 好像就是quad tree。
对于quad tree每一个region,存总的sum, 和所有row的 和 所有column 的sum。. visit 1point3acres.com for more.
递归过程t(n) = t(n/2) +O(n) 因为只有一个quadrant 需要 recursive call, 其他的可以直接根据region 存的值算出来 所以是o(n)