Leetcode 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]]
  • 翻译:

给定在平面上的所有两两不同的点,一个“boomerang”是一个点(i,j,k)的元组,使得i和j之间的距离等于i和k之间的距离 ( 顺序很重要)

找到所有boomerang的数量。 您可以假设n最多为 500 ,点的坐标全部在 [ - 10000,10000] 的范围内。

  • 题解:
class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) 
    {
        int ret = 0;
        for ( int i = 0; i < points.size() ; i++ )
        {
            //对于点[i]的记录map,来记录点i到点集中每个点的位置
            map<int,int> record;
            //遍历除i之外的所有点,以距离为键值,找到到点i距离相同的点有多少个
            //这里特别注意.j是从0开始的,因为对这个问题来说(a,b)(b,a)是两个不同的组合
            for ( int j = 0; j < points.size() ; j++ )
            {
                if ( j != i )
                {
                    //这里采用距离的平方,可以避免浮点数的误差
                    int distance = dis(points[i], points[j]);
                    //找到后record记录中的点数要+1
                    record[distance]++;
                }
            }
            // 计算对每一个点来说的,到两个距离相同点的组合的个数
            int temp = 0;

            for ( map<int,int>::iterator iter = record.begin() ; iter != record.end() ; iter++ )
            {
                //这里要注意,对每一个点来说,不是单纯的加上距离相同点的个数。这是个计数原理的问题,结果是Cn2,因为选择两次,第一次从n个中进行选择,第二次                 //从n-1个中进行选择。(当前点a,候选点b,候选点c)
                temp += (*iter).second * ( (*iter).second - 1 );
            }
            ret += temp;
        }
        return ret;
    }

    int dis(pair<int,int> a,pair<int,int> b)
    {
        int ret = (a.first - b.first) * (a.first - b.first) +
                    (a.second - b.second) * (a.second - b.second);
        return ret;
    }

};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值