
Number of Boomerangs
Problem
给定一个点集。找出能组成的 boomerang 的个数。
boomerang 的定义是一个 (i, j, k) 元组:
满足 distance(i, j) = distance(j, k)
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class { public int numberOfBoomerangs(int[][] points) { Map<Integer, Integer> map = new HashMap<>(); int res = 0; for(int i = 0; i < points.length; i++ ) { for(int j = 0; j < points.length; j++ ) { if(i == j) continue; int d = getDistance(points[i], points[j]); map.put( d, map.getOrDefault(map.get(d), 0) + 1 ); } for(int val : map.values()) { res += val * (val - 1); } map.clear(); } return res; } private int getDistance(int[] a , int[] b) { int x = a[0] - a[0]; int y = a[1] - b[1]; return x*x + y*y; } }
|
近期评论