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     }

 

转载于:https://www.cnblogs.com/wzj4858/p/7718710.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值