题目:
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).
目前只有暴力解法。。。。。就是两个循环。。。。
注意:
-
if(i==j) continue; 因为自己和自己是没有距离的,所以不能考虑这个情况。“continue”语句用来结束当前循环,并进入下一次循环,即仅仅这一次循环结束了,不是所有循环结束了,后边的循环依旧进行。
-
每次第二个循环完要清除一下map,用来计算和保存下一个点和各个点的距离。
-
然后计算有几种情况的时候用这个res += value * (value -1); 因为如果只有两个点到一个点的情况有两种,但是三个点就是六种。
4.算两点距离的时候用到了方法。
5.hashmap.put(distance, hashmap.getOrDefault(distance, 0) + 1);如果没有这个距离的话,就放入1,有的话就把之前的值加1。
Code:
public int numberOfBoomerangs(int[][] points) {
int res = 0;
Map<Integer,Integer> d = new HashMap<Integer,Integer>();
for(int i=0;i<points.length;i++){
for(int j=0;j<points.length;j++){
if(i==j) continue;
int distance = getDistance(points[i], points[j]);
d.put(distance, d.getOrDefault(distance, 0) + 1);
}
for(int value : d.values()){
res += value * (value -1);
}
d.clear();
}
return res;
}
public int getDistance(int[] point1, int[] point2){
int dx= point2[0] - point1[0];
int dy=point2[1] - point1[1];
return dx*dx + dy*dy;
}