首页>itarticle>[lintcode] problem 817 – range sum query 2d – mutable
[lintcode] problem 817 – range sum query 2d – mutable
admin11月 13, 20200
Given a 2D matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). And the elements of the matrix could be changed.
You have to implement three functions:
NumMatrix(matrix) The constructor.
sumRegion(row1, col1, row2, col2) Return the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
update(row, col, val) Update the element at (row, col) to val.
Note
The matrix is only modifiable by update.
You may assume the number of calls to update and sumRegion function is distributed evenly.
public(int m, int n){ sum = newint[m + 1][n + 1]; }
publicvoidupdate(int row, int col, int delta){ for (int i = row; i < sum.length; i += lowbit(i)) { for (int j = col; j < sum[0].length; j += lowbit(j)) sum[i][j] += delta; } }
publicintquery(int row, int col){ int result = 0;
for (int i = row; i > 0; i -= lowbit(i)) { for (int j = col; j > 0; j -= lowbit(j)) result += sum[i][j]; }
近期评论