题目:
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]]
思路:
由于i,j和i,k中均含有i这一公共元素,因此,我们以此为出发点。依次遍历每一组数据,并计算其余元素距该点的距离值(为避免开根号后的小数误差,这里只计算平方和即可),并通过HashMap记录距离,其中key为距离,value为距离出现的次数;每遍历一组数据,记录一次,并计算此时符合题意得次数(由于是有序的,因此次数=value*(value-1)+之前次数),注意计算次数后需要清空HashMap中数据。
程序:
class Solution {
public int numberOfBoomerangs(int[][] points) {
int result = 0;
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int i = 0; i < points.length; i++){ //遍历第i组数据
for(int j = 0; j < points.length; j++){ //遍历其余数据
if(i != j ){
int distance = dis(points[i],points[j]); //调用方法计算距离
if(record.containsKey(distance)) //更改Map记录
record.put(distance,record.get(distance)+1);
else
record.put(distance,1);
}
}
for(int value: record.values()) //遍历Map,计算result
result += value * (value-1);
record.clear(); //清空Map
}
return result;
}
private int dis(int []point1 , int []point2){ //计算距离
int distance = (point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] - point2[1]) * (point1[1] - point2[1]);
return distance;
}
}