You are given npoints in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k(the order of the tuple matters).
For each point, we count how many other points are at each possible distance from it. If there are cnt points at the same distance, there are cnt * (cnt - 1) ways to choose two of them in order, forming boomerangs. We use a hash map to count distances efficiently.
from collections import Counter
classSolution:
defnumberOfBoomerangs(self, points: list[list[int]]) -> int:
ans =0for p in points:
counter = Counter()
for q in points:
dx = p[0] - q[0]
dy = p[1] - q[1]
dist = dx * dx + dy * dy
counter[dist] +=1for cnt in counter.values():
ans += cnt * (cnt -1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintnumberOfBoomerangs(int[][] points) {
int ans = 0;
for (int[] p : points) {
Map<Integer, Integer> counter =new HashMap<>();
for (int[] q : points) {
int distance = (p[0]- q[0]) * (p[0]- q[0]) + (p[1]- q[1]) * (p[1]- q[1]);
counter.put(distance, counter.getOrDefault(distance, 0) + 1);
}
for (int val : counter.values()) {
ans += val * (val - 1);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
functionnumberOfBoomerangs(points: number[][]):number {
letans=0;
for (letp1ofpoints) {
lethashMap: Map<number, number> =newMap();
for (letp2ofpoints) {
constdistance= (p1[0] -p2[0]) **2+ (p1[1] -p2[1]) **2;
hashMap.set(distance, (hashMap.get(distance) ||0) +1);
}
for (let [, v] of [...hashMap]) {
ans+=v* (v-1);
}
}
returnans;
}