题目链接
法一
private int calcDis(int[] p1, int[] p2) {
int dx = p1[0] - p2[0];
int dy = p1[1] - p2[1];
return dx * dx + dy * dy;
}
public int numberOfBoomerangs(int[][] points) {
int cnt = 0;
Map<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
int dis = calcDis(points[i], points[j]);
mp.put(dis, mp.getOrDefault(dis, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
cnt += entry.getValue() * (entry.getValue() - 1);
}
mp.clear();
}
return cnt;
}
法二
private int calcDis(int[] p1, int[] p2) {
int dx = p1[0] - p2[0];
int dy = p1[1] - p2[1];
return dx * dx + dy * dy;
}
public int numberOfBoomerangs_2(int[][] points) {
int cnt = 0;
Map<Integer, Integer> mp = new HashMap<>();
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
int dis = calcDis(points[i], points[j]);
cnt += mp.getOrDefault(dis, 0) * 2;
mp.put(dis, mp.getOrDefault(dis, 0) + 1);
}
mp.clear();
}
return cnt;
}
本地测试
lay.showTitle(447);
Solution447 sol447 = new Solution447();
int[][] points447 = new int[][]{{1, 1},{2, 2},{3, 3}};
System.out.println(sol447.numberOfBoomerangs(points447));
System.out.println(sol447.numberOfBoomerangs_2(points447));