447. Number of Boomerangs

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了447. Number of Boomerangs相关的知识,希望对你有一定的参考价值。

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 iand 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, k)中i和j之间的距离与i和k之间的距离相等。找到一组坐标数据中,可构成几组这样的“回形标”结构。
 1     private int getDistance(int[] p1, int[] p2) {
 2         int x = p1[0] - p2[0];
 3         int y = p1[1] - p2[1];
 4         return x * x + y * y;
 5     }
 6     
 7     public int numberOfBoomerangs(int[][] points) {
 8         if (points.length == 0 || points[0].length == 0) return 0;
 9         int result = 0;
10         for (int i = 0; i < points.length; i++) {
11             Map<Integer, Integer> distances = new HashMap<>();
12             for (int j = 0; j < points.length; j++) {
13                 if (i == j) continue;
14                 int distance = getDistance(points[i], points[j]);
15                 distances.put(distance, distances.getOrDefault(distance, 0) + 1);
16             }
17             for (Integer count : distances.values()) {
18                 result += count * (count - 1); //只有大于两条的才能有值.count个节点距离都相等,任选两条就可以与其它边一起构成会回形标。所以可以构成count * (count - 1)条
19             }
20         }
21         return result;     
22     }

 

以上是关于447. Number of Boomerangs的主要内容,如果未能解决你的问题,请参考以下文章

447. Number of Boomerangs

447. Number of Boomerangs

447. Number of Boomerangs

LeetCode 447 Number of Boomerangs

leetcode447-Number of Boomerangs

[LeetCode]447 Number of Boomerangs