Skip to content

Commit ed0909c

Browse files
authored
Create subrectangle-queries.cpp
1 parent 5106bba commit ed0909c

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

C++/subrectangle-queries.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Time: ctor: O(1)
2+
// update: O(1)
3+
// get: O(u), u is the number of updates
4+
// Space: O(u)
5+
6+
class SubrectangleQueries {
7+
public:
8+
SubrectangleQueries(vector<vector<int>>& rectangle)
9+
: rectangle_(rectangle) {
10+
11+
}
12+
13+
void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
14+
updates_.emplace_back(row1, col1, row2, col2, newValue);
15+
}
16+
17+
int getValue(int row, int col) {
18+
for (int i = updates_.size() - 1; i >= 0; --i) {
19+
const auto& [row1, col1, row2, col2, newValue] = updates_[i];
20+
if (row1 <= row && row <= row2 &&
21+
col1 <= col && col <= col2) {
22+
return newValue;
23+
}
24+
}
25+
return rectangle_[row][col];
26+
}
27+
28+
private:
29+
const vector<vector<int>>& rectangle_;
30+
vector<tuple<int, int, int, int, int>> updates_;
31+
};
32+
33+
// Time: ctor: O(1)
34+
// update: O(m * n)
35+
// get: O(1)
36+
// Space: O(1)
37+
class SubrectangleQueries2 {
38+
public:
39+
SubrectangleQueries2(vector<vector<int>>& rectangle)
40+
: rectangle_(rectangle) {
41+
42+
}
43+
44+
void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {
45+
for (int r = row1; r <= row2; ++r) {
46+
for (int c = col1; c <= col2; ++c) {
47+
rectangle_[r][c] = newValue;
48+
}
49+
}
50+
}
51+
52+
int getValue(int row, int col) {
53+
return rectangle_[row][col];
54+
}
55+
56+
private:
57+
vector<vector<int>>& rectangle_;
58+
};

0 commit comments

Comments
 (0)