原题网址:https://leetcode.com/problems/number-of-boomerangs/
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 i
and 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]]
方法:使用哈希映射保存距离的计数器。
public class Solution {
private void put(Map<Integer, Integer> map, int d) {
Integer count = map.get(d);
if (count == null) {
count = 1;
} else {
count++;
}
map.put(d, count);
}
public int numberOfBoomerangs(int[][] points) {
Map<Integer, Integer> distance = new HashMap<>();
int numbers = 0;
for(int i = 0; i < points.length; i++) {
distance.clear();
for(int j = 0; j < points.length; j++) {
if (j == i) continue;
int dx = points[i][0] - points[j][0];
int dy = points[i][1] - points[j][1];
int d2 = dx * dx + dy * dy;
put(distance, d2);
}
for(Map.Entry<Integer, Integer> entry : distance.entrySet()) {
int v = entry.getValue();
if (v < 2) continue;
numbers += v * (v - 1);
}
}
return numbers;
}
}