Google
447 Number of Boomerangs

1. Question

Givennpoints in the plane that are all pairwise distinct, a "boomerang" is a tuple of points(i, j, k)such that the distance betweeniandjequals the distance betweeniandk(the order of the tuple matters).
Find the number of boomerangs. You may assume thatnwill be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:
1
Input: [[0,0],[1,0],[2,0]]
2
3
Output: 2
4
5
Explanation:
6
7
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
Copied!

2. Implementation

思路: (1) 对每个point A,我们都找出它和其他点所形成的距离
(2) 将这些距离存入一个hashmap中,key是距离的值,value是和point A构成这个距离值得点的个数
(3) 接下来如果point A对应的是boomerang的i, 那么我们接下来要求(j, k)的总排列. 遍历hashmap,对于每个key对应的value,根据排列公式 n!/ (n - 2)! = n(n - 1), 能形成boomberangs的个数等于 value * (value - 1)
1
class Solution {
2
public int numberOfBoomerangs(int[][] points) {
3
int res = 0;
4
Map<Integer, Integer> map = new HashMap<>();
5
6
for (int i = 0; i < points.length; i++) {
7
for (int j = 0; j < points.length; j++) {
8
int distance = getDistance(points[i], points[j]);
9
10
map.put(distance, map.getOrDefault(distance, 0) + 1);
11
}
12
13
for (Integer value : map.values()) {
14
res += value * (value - 1);
15
}
16
map.clear();
17
}
18
return res;
19
}
20
21
public int getDistance(int[] p1, int[] p2) {
22
int dx = p1[0] - p2[0];
23
int dy = p1[1] - p2[1];
24
return dx * dx + dy * dy;
25
}
26
}
Copied!

3. Time & Space Complexity

时间复杂度O(n^2), 空间复杂度O(n)