447. Number of Boomerangs

本文探讨了在平面上寻找特定几何结构“回旋镖”的高效算法。通过使用哈希映射,文章提供了两种方法来解决这个问题:一种是直接但效率较低的方法,另一种是优化后的哈希方法,后者的时间复杂度为O(n^2),空间复杂度为O(n)。通过实例说明了如何在给定点集上应用这些算法。


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

方法1: hash map, TLE

思路:

最后一个大数据点TLE。事实上没有必要将所有点的数据都存下来,每一个点的hash数据在后面都不会用到。

class Solution {
public:
    int numberOfBoomerangs(vector<vector<int>>& points) {
        map<vector<int>, unordered_map<double, int>> hash;
        for (int i = 0; i < points.size(); i++) {
            for (int j = i + 1; j < points.size(); j++) {
                auto p1 = points[i];
                auto p2 = points[j];
                double d = pow((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]), 0.5);
                hash[points[i]][d]++;
                hash[points[j]][d]++;
            }
        }
        int res = 0;
        for (auto a: hash) {
            for (auto v: a.second) {
                res += v.second * (v.second - 1);
            }
        }
        return res;
    }
};

方法2: better hash

思路:

遍历每一个点时,针对该点建立一个新的hash,意义是distancd : count, i.e. 距离该点为d的其他点数量。统计结束后即可找到当前点为轴心所有boomarang的配对。由于位置可换,所以是permutation。

Complexity

Time complexity: O(n^2)
Space complexity: O(n)

class Solution {
public:
    int numberOfBoomerangs(vector<vector<int>>& points) {
        unordered_map<double, int> hash;
        int res = 0;
        for (int i = 0; i < points.size(); i++) {
            for (int j = 0; j < points.size(); j++) {
                if (i == j) continue;
                auto p1 = points[i];
                auto p2 = points[j];
                double d = pow((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]), 0.5);
                hash[d]++;
            }
            for (auto a: hash) {
                res += a.second * (a.second - 1);
            }
            hash.clear();
        }
       
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值