[LeetCode] Subrectangle Queries

1476. Subrectangle Queries

Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:

  • updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
  • Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
  • getValue(int row, int col)
  • Returns the current value of the coordinate (row,col) from the rectangle.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class SubrectangleQueries {
vector<vector<int>> rec;
vector<vector<int>> his;
public:
SubrectangleQueries(vector<vector<int>>& rectangle) {
rec = rectangle;
}

void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
his.push_back({row1, col1, row2, col2, newValue});
}

int getValue(int row, int col) {
for(int i = his.size() - 1; i >= 0; i--) {
int r1 = his[i][0], c1 = his[i][1], r2 = his[i][2], c2 = his[i][3], v = his[i][4];
if(r1 <= row and row <= r2 and c1 <= col and col <= c2) return v;
}
return rec[row][col];
}
};

/**
* Your SubrectangleQueries object will be instantiated and called as such:
* SubrectangleQueries* obj = new SubrectangleQueries(rectangle);
* obj->updateSubrectangle(row1,col1,row2,col2,newValue);
* int param_2 = obj->getValue(row,col);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/19/PS/LeetCode/subrectangle-queries/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.