Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points
(i, j, k) such that the distance between iand j equals the distance between i and k (the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000](inclusive).
Example:
Input: [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
For each point, we use a map to track the distance and number of points seen for this distance. Total number of points with same distance should be x * (x - 1) where x is the number of points with a calculated distance from this point.
public int numberOfBoomerangs(int[][] points) {
if (points.length == 0) {
return 0;
}
int sum = 0;
int len = points.length;
for (int i = 0; i < len; i++) {
Map distances = new HashMap<>();
for (int j = 0; j < len; j++) {
if (i == j) {
continue;
}
int distance = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1]);
distances.put(distance, distances.getOrDefault(distance, 0) + 1);
}
sum += distances.values().stream().mapToInt(x -> x * (x - 1)).sum();
}
return sum;
}
No comments:
Post a Comment