Detect Squares LeetCode solution in C++

1
class DetectSquares {
2
public:
3
vector<unordered_map<int, int>> x_axis;
4

5
DetectSquares() {
6
x_axis = vector<unordered_map<int, int>>(1005);
7
}
8

9
void add(vector<int> point) {
10
int x = point[0];
11
int y = point[1];
12
x_axis[x][y]++;
13
}
14

15
int count(vector<int> point) {
16
int x = point[0], y = point[1];
17
int res = 0;
18
for (auto &it : x_axis[x]) { // For all points lying on x_axis with value
19
// x_coordinate = x
20
int y_coord = it.first;
21
int countOcc = it.second;
22

23
if (y == y_coord) continue;
24
int sideLength = abs(y_coord - y);
25

26
// counting for p3' and p4'
27
if (x + sideLength <= 1000) // x_coordinate should be within range [0, 1000]
28
{
29
int newX = x + sideLength;
30
res += x_axis[x][y_coord] * x_axis[newX][y_coord] * x_axis[newX][y];
31
}
32

33
// counting for p3'' and p4''
34
if (x - sideLength >= 0) // x_coordinate should be within range [0, 1000]
35
{
36
int newX = x - sideLength;
37
res += x_axis[x][y_coord] * x_axis[newX][y_coord] * x_axis[newX][y];
38
}
39
}
40
return res;
41
}
42
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0