zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    js字符串使用占位符拼接
    C#解析json字符串总是多出双引号的原因分析及解决办法
    JS 正则验证字符串中是否含有数字
    不错的MVC文章
    Js 更换html同一父元素下子元素的位置
    团队任务个人博客--20160426
    《构建之法》阅读笔记3
    团队任务个人博客20160425
    团队任务个人博客20160424
    软件工程进度条-第八周
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6551916.html
Copyright © 2011-2022 走看看