Givennpoints in the plane that are all pairwise distinct, a "boomerang" is a tuple of points(i, j, k)
such that the distance betweeni
andj
equals the distance betweeni
andk
(the order of the tuple matters ).
Find the number of boomerangs. You may assume thatnwill be at most500 and coordinates of points are all in the range[-10000, 10000] (inclusive).
Copy class Solution {
private int getDistance(int[] a, int[] b) {
int dx = a[0] - b[0];
int dy = a[1] - b[1];
return dx*dx + dy*dy;
}
public int numberOfBoomerangs(int[][] points) {
Map[] maps = new Map[points.length];
for (int i = 0; i < points.length; i++) {
maps[i] = new HashMap<Integer, Integer>();
Map<Integer, Integer> map = maps[i];
for (int j = 0; j < points.length; j++) {
if (j == i) {
continue;
}
int distance = getDistance(points[i], points[j]);
if (!map.containsKey(distance)) {
map.put(distance, 1);
} else {
map.put(distance, (int)map.get(distance) + 1);
}
}
}
int res = 0;
for (Map<Integer, Integer> map : maps) {
for (Integer dis : map.keySet()) {
if (map.get(dis) > 1) {
res += map.get(dis) * (map.get(dis) - 1);
}
}
}
return res;
}
}
时间复杂度O(n^2), 空间O(n^2).
可以重复利用一个map.
Copy class Solution {
private int getDistance(int[] a, int[] b) {
int dx = a[0] - b[0];
int dy = a[1] - b[1];
return dx*dx + dy*dy;
}
public int numberOfBoomerangs(int[][] points) {
int res = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length; j++) {
if (j == i) {
continue;
}
int distance = getDistance(points[i], points[j]);
if (!map.containsKey(distance)) {
map.put(distance, 1);
} else {
map.put(distance, (int)map.get(distance) + 1);
}
}
for (Integer dis : map.keySet()) {
if (map.get(dis) > 1) {
res += map.get(dis) * (map.get(dis) - 1);
}
}
map.clear();
}
return res;
}
}