/**
* Using a hashmap to save the pair of <distance, count>
* Find all 2-permutations of N, P(n, 2) = n*(n-1)
* Increase the count when distance is already in the map.
* Sum up the count, another 2-permutations of count.
*/
public class Solution {
public int numberOfBoomerangs(int[][] points) {
int dist = 0, ret = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// do 2-permutations of n
for (int i=0; i<points.length; i++) {
for (int j=0; j<points.length; j++) {
if (i == j) continue;
dist = calDist(points, i, j);
// increase count when dist is already in the map
if (map.containsKey(dist))
map.put(dist, map.get(dist)+1);
else
map.put(dist, 1);
}
// count the total number of paires
// e.g. for record <dist1, 4>, there are total 4*3 different paires, the order of the tuple matters*
// 1, 2, 3 and 1, 3, 2 are different
for (int cnt : map.values())
ret += cnt * (cnt-1);
// starting next point
map.clear();
}
return ret;
}
// we don't have to calculate the exactely distance between two points,
// instead just return (x1-x2)^2+(y1-y2)^2
public static int calDist(int[][] points, int i, int j) {
// dist = sqrt((x1-x2)^2+(y1-y2)^2)
int x = (points[i][0]-points[j][0]) * (points[i][0]-points[j][0]);
int y = (points[i][1]-points[j][1]) * (points[i][1]-points[j][1]);
return x + y;
}
}
/** * Using a hashmap to save the pair of * Find all 2-permutations of N, P(n, 2) = n*(n-1) * Increase the count when distance is already in the map. * Sum up the count, another 2-permutations of