447. Number of Boomerangs(LeetCode)

本文介绍了一种算法,用于计算给定点集中的回旋镖数量。回旋镖定义为三个点 (i,j,k),其中点 i 到 j 和 i 到 k 的距离相等,并且考虑点的顺序。文章提供了两种实现方法:一种使用欧几里得距离平方进行计算,另一种则利用了 C++ 的标准库函数。

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 andj 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 int numberOfBoomerangs(vector<pair<int, int>>& points) {
 2     
 3     int res = 0;
 4     
 5     // iterate over all the points
 6     for (int i = 0; i < points.size(); ++i) {
 7         
 8         unordered_map<long, int> group(points.size());
 9         
10         // iterate over all points other than points[i]
11         for (int j = 0; j < points.size(); ++j) {
12             
13             if (j == i) continue;
14             
15             int dy = points[i].second - points[j].second;
16             int dx = points[i].first - points[j].first;
17             
18             // compute squared euclidean distance from points[i]
19             int key = dy * dy;
20             key += dx * dx;
21             
22             // accumulate # of such "j"s that are "key" distance from "i"
23             ++group[key];
24         }
25         
26         for (auto& p : group) {
27             if (p.second > 1) {
28                 /*
29                  * for all the groups of points, 
30                  * number of ways to select 2 from n = 
31                  * nP2 = n!/(n - 2)! = n * (n - 1)
32                  */
33                 res += p.second * (p.second - 1);
34             }
35         }
36     }
37     
38     return res;
39 }
int numberOfBoomerangs(vector<pair<int, int>>& points) {
    int booms = 0;
    for (auto &p : points) {
        unordered_map<double, int> ctr(points.size());
        for (auto &q : points)
            booms += 2 * ctr[hypot(p.first - q.first, p.second - q.second)]++;
    }
    return booms;
}

 

转载于:https://www.cnblogs.com/wujufengyun/p/6839144.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值