码迷,mamicode.com
首页 > 其他好文 > 详细

447. Number of Boomerangs

时间:2017-10-23 20:46:55      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:color   point   mos   att   含义   nbsp   oom   i++   tin   

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

标签:color   point   mos   att   含义   nbsp   oom   i++   tin   

原文地址:http://www.cnblogs.com/wzj4858/p/7718710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!