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 betweeni and 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)的个数

    • 1.要求(i,j)的欧氏距离等于(i,k)

    • 2.(i,k,j)(j,k,i)为不同

    
    public int distance(int a[],int b[])
        {
            int x = a[0] - b[0];
            int y = a[1] - b[1];
            return x*x + y*y;
        }
        public int numberOfBoomerangs(int[][] points) {//[a,b,c,d]
            int result = 0;
            HashMap<Integer,Integer> map = new HashMap<>();
            for(int i  = 0; i < points.length; i++)
            {
                for(int j = 0; j < points.length ; j++) //内层循环,计算ab,ac,ad距离
                {
                    if(i != j)
                    {
                        int dis = distance(points[i], points[j]);
                        map.put(dis, map.getOrDefault(dis, 0) + 1); //类似python a.get(key,default)
                    }
                }
                for(int val:map.values()) 
                    result += val * (val-1); //全排列 A(n,2)
                map.clear(); //清空map
            }
            
            return result;
        }
    

    在一次循环中,遍历所有的点,找出任意两个点的距离,例如(ab,ac,ad),并保存距离为d个组合个数n。由于条件2,相当于全排列A(n,2)

    知识点:

    • 1.map获取值的方式map.getOrDefault(Object key, Integer defaultValue)类似与python的dict的get

    • 2.map.values的用法,类似的有map.keySet()

  • 相关阅读:
    nginx一键安装脚本
    nginx动静分离之后,设置默认主页
    日志备份
    cc高防主机部署
    原型和原型链
    Git&Github分支
    Git&Github基础
    传输层协议TCP&UDP
    本地库与远程库交互
    SVG
  • 原文地址:https://www.cnblogs.com/wxshi/p/7764951.html
Copyright © 2011-2022 走看看