Skip to content

Commit 7210c74

Browse files
authored
Create number-of-corner-rectangles.cpp
1 parent d43f272 commit 7210c74

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

C++/number-of-corner-rectangles.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(m^2 * n), m is the number of rows with 1s, n is the number of cols with 1s
2+
// Space: O(m * n)
3+
4+
class Solution {
5+
public:
6+
int countCornerRectangles(vector<vector<int>>& grid) {
7+
vector<vector<int>> rows;
8+
for (int i = 0; i < grid.size(); ++i) {
9+
vector<int> row;
10+
for (int j = 0; j < grid[i].size(); ++j) {
11+
if (grid[i][j]) {
12+
row.emplace_back(j);
13+
}
14+
}
15+
if (!row.empty()) {
16+
rows.emplace_back(move(row));
17+
}
18+
}
19+
int result = 0;
20+
for (int i = 0; i < rows.size(); ++i) {
21+
unordered_set<int> lookup(rows[i].begin(), rows[i].end());
22+
for (int j = 0; j < i; ++j) {
23+
int count = 0;
24+
for (const auto& c : rows[j]) {
25+
count += lookup.count(c);
26+
}
27+
result += count * (count - 1) / 2;
28+
}
29+
}
30+
return result;
31+
}
32+
};

0 commit comments

Comments
 (0)