File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n^2)
2
+ // Space: O(n^2)
3
+
4
+ // hash table
5
+ class Solution {
6
+ public:
7
+ int equalPairs (vector<vector<int >>& grid) {
8
+ unordered_map<vector<int >, int , VectorHash<int >> cnt1;
9
+ for (const auto & row : grid) {
10
+ ++cnt1[row];
11
+ }
12
+ unordered_map<vector<int >, int , VectorHash<int >> cnt2;
13
+ for (int j = 0 ; j < size (grid[0 ]); ++j) {
14
+ vector<int > col (size (grid));
15
+ for (int i = 0 ; i < size (grid); ++i) {
16
+ col[i] = grid[i][j];
17
+ }
18
+ ++cnt2[col];
19
+ }
20
+ int result = 0 ;
21
+ for (const auto & [k, _] : cnt1) {
22
+ if (!cnt2.count (k)) {
23
+ continue ;
24
+ }
25
+ result += cnt1[k] * cnt2[k];
26
+ }
27
+ return result;
28
+ }
29
+
30
+ private:
31
+ template <typename T>
32
+ struct VectorHash {
33
+ size_t operator ()(const std::vector<T>& v) const {
34
+ size_t seed = 0 ;
35
+ for (const auto & i : v) {
36
+ seed ^= std::hash<T>{}(i) + 0x9e3779b9 + (seed<<6 ) + (seed>>2 );
37
+ }
38
+ return seed;
39
+ }
40
+ };
41
+ };
You can’t perform that action at this time.
0 commit comments