447. Number of Boomerangs

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
class Solution {
public int numberOfBoomerangs(int[][] points) {
int count = 0;

for (int i = 0; i < points.length; i++) {
// 计算出与其他点的距离
Map<Integer, Integer> powerToCountMap = new HashMap<>();

// 以当前点为中点,枚举另一个点
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
int xDistance = points[j][0] - points[i][0], yDistance = points[j][1] - points[i][1];
int powerDistance = xDistance * xDistance + yDistance * yDistance;

int sameDistanceCount = powerToCountMap.getOrDefault(powerDistance, 0);
count += sameDistanceCount * 2; // 可以组成回旋镖,则累加两倍元组
powerToCountMap.put(powerDistance, sameDistanceCount + 1);
}
}

return count;
}
}

以为有什么优于 O(n^2) 的解法,结果并没有。

References

447. Number of Boomerangs