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]]

本题虽然是easy题目,但是题目确实还是挺不好想的,首先我们要明白,原问题要求我们求出相同距离,而之前的题目Line reflection要求我们求对称线,Max lines on a plane要求我们求
k值相同。那么问题来了,怎么求出相同距离呢,我们这里需要用到圆的概念:圆心到圆上任意点的距离相等。接下来再处理一下boomerang的概念,即:寻找有多少对等长的线段*2;代码如下:
 1 public class Solution {
 2     public int numberOfBoomerangs(int[][] points) {
 3         Map<Integer,Integer> map = new HashMap<>();
 4         int res= 0 ;
 5         for(int i=0;i<points.length;i++){
 6             for(int j=0;j<points.length;j++){
 7                 if(i==j) continue;
 8                 int dis = distance(points[i],points[j]);
 9                 map.put(dis,map.getOrDefault(dis,0)+1);
10             }
11             int val = 0;
12             for(int v:map.values()){
13                 val+=v*(v-1);
14             }
15             res+=val;
16             map.clear();
17         }
18         return res;
19     }
20     public int distance(int[] a,int[] b){
21         int x = a[0]-b[0];
22         int y = a[1]-b[1];
23         return x*x+y*y;
24     }
25 }

 

posted @ 2017-03-15 06:02  CodesKiller  阅读(85)  评论(0编辑  收藏  举报