LeetCode-Easy部分标签为HashTable 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 i 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]]

题目分析

给出n组点,找出所有boomerang 的个数,boomerang 定义: d(Pi,Pj)=d(Pi,Pk)。题目涉及到三个点,先保持一个轴点rot,然后找与其他点的距离,若个数为m,m满足m>1,则找到轴点rotBoomerangs 个数为A(m,2) ,继续遍历其他轴点,返回累加和。

代码分析

        public static int NumberOfBoomerangs(int[,] points)
        {
            Dictionary<double, int> dict = new Dictionary<double, int>();
            int len = points.GetUpperBound(0);
            int rtnCnt=0;
            for (int i = 0; i <= len; i++)
            {
                //3点变2点
                for (int j = 0; j <= len; j++)
                {
                    if (i == j) continue;
                    double d = distance(points[i, 0], points[j, 0], points[i, 1], points[j, 1]);
                    if (dict.ContainsKey(d))
                        dict[d]++;
                    else dict.Add(d, 1);
                }
                foreach(var item in dict)
                {
                    if (item.Value > 1)
                    {
                        //如果找到了value个,因为有顺序,所以排序
                        rtnCnt += item.Value*(item.Value-1); 
                    }
                }
                dict.Clear();
            }
            return rtnCnt;
        }

        private static double distance(int x1, int x2, int y1, int y2)
        {
            int x = x1 - x2;
            int y = y1 - y2;

            return Math.Sqrt(x * x + y * y);
        }

结果分析

算法运行时间为 Runtime: 372 ms,排名85%
时间复杂度O(n^2),控件复杂度O(n)。


这里写图片描述

更多参考

LeetCode-Easy部分中标签为HashTable的所有题目

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值