当前位置:网站首页>308. 2D area and retrieval - variable segment tree / hash
308. 2D area and retrieval - variable segment tree / hash
2022-06-27 20:43:00 【Empress Yu】
308. Two dimensional region and retrieval
Here's a two-dimensional matrix for you
matrix, You need to handle several queries of the following two types :
- to update : to update
matrixThe value of a cell in .- Sum up : Calculation of matrix
matrixOf a rectangular area element in and , This area is controlled by top left corner(row1, col1)and The lower right corner(row2, col2)Definition .Realization
NumMatrixclass :
NumMatrix(int[][] matrix)Using integer matrixmatrixInitialize object .void update(int row, int col, int val)to updatematrix[row][col]Value toval.int sumRegion(int row1, int col1, int row2, int col2)Return matrixmatrixOf the rectangular area element specified in and , This area is controlled by top left corner(row1, col1)and The lower right corner(row2, col2)Definition .Example 1:
Input ["NumMatrix", "sumRegion", "update", "sumRegion"] [[[[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]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]] Output [null, 8, null, 10] explain NumMatrix numMatrix = new NumMatrix([[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]]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 ( namely , The sum of the red rectangle on the left ) numMatrix.update(3, 2, 2); // The matrix changes from left to right numMatrix.sumRegion(2, 1, 4, 3); // return 10 ( namely , And of the red rectangle on the right )Tips :
m == matrix.lengthn == matrix[i].length1 <= m, n <= 200-105 <= matrix[i][j] <= 10^50 <= row < m0 <= col < n-105 <= val <= 10^50 <= row1 <= row2 < m0 <= col1 <= col2 < n- Call at most
10^4TimesumRegionandupdateMethod
The result of doing the question
success , Two solutions are used
Method 1: Hash
Lazy loaded two-dimensional prefix and , The good thing is always update Or always sum , Complexity is still O(1), Alternate is O(mn)
1. Initialize prefix and
2. When updating data , Mark
3. When getting marked , Update the array , Remove the mark
class NumMatrix {
int[][] arr;
int[][] pre;
int m;
int n;
boolean hasChange;
public NumMatrix(int[][] matrix) {
arr = matrix;// Change prefix and ...
m = matrix.length;
n = matrix[0].length;
pre = new int[m+1][n+1];
for(int i = 0; i<m; i++){
for(int j = 0; j < n; j++){
pre[i+1][j+1]=matrix[i][j]+pre[i][j+1]+pre[i+1][j]-pre[i][j];
}
}
}
public void update(int row, int col, int val) {
arr[row][col] = val;
hasChange = true;
}
public int sumRegion(int row1, int col1, int row2, int col2) {
if(hasChange){
for(int i = 0; i<m; i++){
for(int j = 0; j < n; j++){
pre[i+1][j+1]=arr[i][j]+pre[i][j+1]+pre[i+1][j]-pre[i][j];
}
}
hasChange = false;
}
return pre[row2+1][col2+1]+pre[row1][col1]-pre[row1][col2+1]-pre[row2+1][col1];
}
}Method 2: Line segment tree
This problem is actually a two-dimensional line segment tree , Record the upper left and lower right corners , There are four points
1. Create a line tree , There are four points , One and , Two children
2. When recursively assigning children , Preferred Branch , Reclassification 【 convenient , Four at a time is OK , There will be more to judge 】
3. Calculate the child's value , Push up one by one , Get the whole prefix and
4. Additive elements : Returns... Out of range , Recursively add... Within the scope , Pass it on to the child
5. Sum up : Current range value , All return directly within the target range sum; Do not return directly within the target 0; Otherwise, the child's sum will be accumulated
class NumMatrix {
SquareTree tree;
int[][] arr;
public NumMatrix(int[][] matrix) {
arr = matrix;
tree = new SquareTree(0,0,matrix.length-1,matrix[0].length-1,matrix);
}
public void update(int row, int col, int val) {
int diff = val-arr[row][col];
arr[row][col] = val;
tree.add(row,col,diff);
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return tree.getSum(row1,col1,row2,col2);
}
}
class SquareTree{
int x1;
int x2;
int y1;
int y2;
int sum;
SquareTree t1;
SquareTree t2;
public SquareTree(int x1, int y1, int x2, int y2,int[][] arr){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
sum = initSum(x1,y1,x2,y2,arr);
}
private int initSum(int X1, int Y1, int X2, int Y2, int[][] arr){
if(X1==X2 && Y1 == Y2){
sum = arr[X1][Y1];
return sum;
}
if(x1<x2){
int mid = (x2-x1)/2+x1;
t1 = new SquareTree(x1,y1,mid,y2,arr);
t2 = new SquareTree(mid+1,y1,x2,y2,arr);
}else{
int mid = (y2-y1)/2+y1;
t1 = new SquareTree(x1,y1,x2,mid,arr);
t2 = new SquareTree(x1,mid+1,x2,y2,arr);
}
sum = t1.sum+t2.sum;
return sum;
}
public void add(int x, int y,int v){
if(x<x1||x>x2||y<y1||y>y2){
return;
}
sum += v;
if(t1!=null)
t1.add(x,y,v);
if(t2!=null)
t2.add(x,y,v);
}
public int getSum(int X1, int Y1, int X2, int Y2){
if(x2<X1||x1>X2||y2<Y1||y1>Y2){
return 0;
}
// All within the scope
if(X1<=x1&&X2>=x2&&Y1<=y1&&Y2>=y2){
return sum;
}
return t1.getSum(X1,Y1,X2,Y2)+t2.getSum(X1,Y1,X2,Y2);
}
}边栏推荐
- Postman 汉化教程(Postman中文版)
- linux系统笑着玩Oracle数据库多表查询-连接查询
- 一场分销裂变活动,不止是发发朋友圈这么简单
- A distribution fission activity is more than just a circle of friends
- SQL audit platform permission module introduction and account creation tutorial
- At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions
- Common shell script commands (III)
- 动物养殖生产虚拟仿真教学系统|华锐互动
- Type the URL to the web page display. What happened during this period?
- Linux system plays Oracle database multi table query connection query with a smile
猜你喜欢

Cloud native Security Guide: learn kubernetes attack and defense from scratch

低代码开发平台是什么?为什么现在那么火?

Redis集群

基于微信小程序的高校党员之家服务管理系统系统小程序#毕业设计,党员,积极分子,学习,打卡,论坛

Installation and configuration of grayog new generation log collection early warning system

pfSense Plus22.01中文定制版发布

CSDN skill tree experience and product analysis (1)
![[STL programming] [common competition] [Part 3]](/img/15/0c397d74128268e17897615ad1c84e.png)
[STL programming] [common competition] [Part 3]

Hash table - Review

Summary of redis big key problem handling
随机推荐
在开发数字藏品时,文博机构该如何把握公益和商业的尺度?如何确保文物数据的安全?
Redis cluster
Openharmony hisysevent dotting and calling practice of # Summer Challenge (L2)
redis数据结构
SQL审核平台权限模块介绍和账号创建教程
Paste source layer and history layer of data warehouse system
ABAP essays - interview memories hope that everyone's demand will not increase and the number of people will soar
Database lock problem
UOS prompts for password to unlock your login key ring solution
Oracle architecture summary
最佳实践:优化Postgres查询性能(下)
Character interception triplets of data warehouse: substrb, substr, substring
花了6个月时间完成本科优秀毕业设计,我做了什么?
Logcli-loki 命令行工具
【STL编程】【竞赛常用】【part 2】
Structs in trust
智联招聘的基于 Nebula Graph 的推荐实践分享
CSDN skill tree experience and product analysis (1)
Mobile low code development theme month | visual development one click generation of professional source code
SQL报了一个不常见的错误,让新来的实习生懵了
