BiruLyu
6/27/2017 - 5:04 PM

## 447. Number of Boomerangs(1st).java

``````public class Solution {
public int getDistance(int[] points1, int[] points2) {
int x = points1[0] - points2[0];
int y = points1[1] - points2[1];
return x * x + y * y;
}
public int numberOfBoomerangs(int[][] points) {
if (points == null || points.length < 3) return 0;
int res = 0;
for (int i = 0; i < points.length; i++) {
Map<Integer, Integer> map = new HashMap<>();
for (int j = 0; j < points.length; j++) {
if (i == j) continue;
int d = getDistance(points[i], points[j]);
map.put(d, map.getOrDefault(d, 0) + 1);
}

for (int val : map.values()) {
res += val * (val - 1);
}
}
return res;
}
}``````
``````public class Solution {
public int numberOfBoomerangs(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;
}
}``````