447. 回旋镖的数量

447. 回旋镖的数量

解法一: 哈希

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func numberOfBoomerangs(points [][]int) int {
ans := 0
for _, point1 := range points {
distanceHash := make(map[int]int)
for _, point2 := range points {
distanceHash[(point2[0] - point1[0]) * (point2[0] - point1[0]) + (point2[1] - point1[1]) * (point2[1] - point1[1])]++
}
for _, count := range distanceHash {
if count > 1 {
ans += count * (count - 1)
}
}
}
return ans
}
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int numberOfBoomerangs(int[][] points) {
int ans = 0;
Map<Integer, Integer> distanceHash = new HashMap<>();
for (int[] point1 : points) {
distanceHash.clear();
for (int[] point2 : points) {
int distance = (point2[0] - point1[0]) * (point2[0] - point1[0]) + (point2[1] - point1[1]) * (point2[1] - point1[1]);
distanceHash.put(distance, distanceHash.getOrDefault(distance, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : distanceHash.entrySet()) {
int count = entry.getValue();
ans += (count - 1) * count;
}
}
return ans;
}
}
作者

wuhunyu

发布于

2024-01-08

更新于

2024-01-08

许可协议