-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
2013-Detect-Squares.js
52 lines (42 loc) · 1.36 KB
/
2013-Detect-Squares.js
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
50
51
52
/*
* Time O(N) | Space O(N)
* https://leetcode.com/problems/detect-squares
*/
class DetectSquares {
constructor () {
this.map = {}; /* Space O(N) */
this.points = [];/* Space O(N) */
}
add (point, { map, points } = this) {
const [ x, y ] = point;
const key = this.getKey(x, y);
const value = ((map[key] || 0) + 1);
map[key] = value; /* Space O(N) */
points.push(point);/* Space O(N) */
}
count (point, { points } = this, score = 0) {
const [ x1, y1 ] = point;
for (const [ x2, y2 ] of points) {/* Time O(N) */
const isSame = (Math.abs(x2 - x1) === Math.abs(y2 - y1));
const isEqual = ((x1 === x2) || (y1 === y2));
const canSkip = (!isSame || isEqual);
if (canSkip) continue;
score += this.getScore(x1, y1, x2, y2);
}
return score;
};
getKey (x, y) {
return `${x},${y}`;
}
getScore (x1, y1, x2, y2, { map } = this) {
const [ aKey, bKey ] = [ this.getKey(x1, y2), this.getKey(x2, y1) ];
const [ aScore, bScore ] = [ (map[aKey] || 0), (map[bKey] || 0) ];
return (aScore * bScore);
}
};
/**
* Your DetectSquares object will be instantiated and called as such:
* var obj = new DetectSquares()
* obj.add(point)
* var param_2 = obj.count(point)
*/