题目: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).
例如: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]]
其实就是寻找原数组中距离相同的点的个数。
思路:嵌套遍历数组两次,第一次为要计算距离的点,内循环是计算其他点到该点的距离。并使用hashMap存储距离信息。代码如下所示(本段代码击败了45%的用户):
public int numberOfBoomerangs2(int[][] points) {
int result = 0;
HashMap<Integer,Integer> distMap = new HashMap<Integer,Integer>();
for(int[] i : points) {
for(int[] j : points) {
if(i==j) continue;
int dist = (i[0]-j[0])*(i[0]-j[0]) + (i[1]-j[1])*(i[1]-j[1]);
int prevDist = distMap.containsKey(dist) ? distMap.get(dist) : 0;
result += 2*prevDist;
distMap.put(dist, prevDist+1);
}
distMap.clear();
}
return result;
}
但是使用下面的代码却达到78%的胜率,二者的思路是完全相同的,不知道速度提升在哪里:
public int numberOfBoomerangs3(int[][] p) {
int n = p.length;
if(n==0) return 0;
int count = 0;
for(int i=0;i<n;i++){
Map<Double,Integer> map = new HashMap<>();
for(int j=0;j<n;j++){
if(map.containsKey(distance(p[i],p[j]))){
int value = map.get(distance(p[i],p[j]));
count+=2*value;
map.put(distance(p[i],p[j]),value+1);
} else {
map.put(distance(p[i],p[j]),1);
}
}
}
return count;
}
public Double distance(int[] a, int[]b){
return Math.sqrt(Math.pow(a[0]-b[0],2) + Math.pow(a[1]-b[1],2));
}