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

【问题分析】

 1、这个题目很容易想到用三层循环,但是会直接超时

 2、防止超时,需要进一步分析

 3、由于数字对是不同,且三元组是有序的

      那么,我们用大写字母标识一个数字对,一个数字对序列是[A,B,C,D,E]

      当三元组是(Ai,Ai1,Ai2)时,只需要和Ai的距离相等的所有数字对任意取2个即可,

      因此对每一个i,只需要计算和Ai距离相等的数字对的个数num,然后任意取2个,排列数结果为num*(num-1),

      即是第i个数对是三元组中的第一个数对时,可能的boomerangs个数,

      那么所有的i,numi*(numi-1)求和,即为总的boomerangs个数

【AC代码】

  

class Solution {
public:
    int numberOfBoomerangs(vector<pair<int, int>>& points) {
            int count = 0;
            for (int i = 0; i < points.size(); ++i) {
                std::map<int,int> m;
                for (int j = 0; j < points.size(); ++j) {
                    if (i == j) {
                        continue;
                    }
                    int dist = distant(points[i], points[j]);
                    ++m[dist];
                }

                for (std::map<int,int>::iterator iter = m.begin(); iter != m.end(); ++iter) {
                    count += iter->second * (iter->second - 1);
                }

            }

            return count;
        }

        int distant(std::pair<int,int> point1, std::pair<int,int> point2) {
            int x = point1.first - point2.first;
            int y = point1.second - point2.second;

            return x*x + y*y;
        }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值