-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2352.cpp
More file actions
49 lines (44 loc) · 1.17 KB
/
2352.cpp
File metadata and controls
49 lines (44 loc) · 1.17 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// time: average case O(n^2)
// alg
// let rowBag be a bag indexed over the relevant vector space.
// for each row in grid O(n)
// rowBag.add(row) O(1)
// let pairs = 0
// for column in grid O(n)
// if (rowBag.contains(column)) O(1)
// pairs += rowBag.count(column) O(1)
//
#include <vector>
#include <unordered_map>
struct VecHash {
size_t operator()(const vector<int>& v) const noexcept {
// simple rolling‐hash
size_t h = v.size();
for (int x : v) {
h = h * 31 + hash<int>()(x);
}
return h;
}
};
class Solution {
public:
int equalPairs(vector<vector<int>>& grid) {
int n = grid.size();
unordered_map<vector<int>, int, VecHash> rowBag;
for (auto& row : grid) {
rowBag[row]++;
}
int pairs = 0;
vector<int> col(n);
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
col[i] = grid[i][j];
}
auto it = rowBag.find(col);
if (it != rowBag.end()) {
pairs += it->second;
}
}
return pairs;
}
};