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]]
方法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;
}
};