leetcode解题: Number of Boomerangs (447)

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:O(N^2)

排列组合的题。假设有a,b,c。如果bc和a的距离相等,那么可以产生abc或者acb两种排列。如果是bcd和a的距离相等,那么可以产生6种排列。对于有n个数和a相等的情况,总共的个数是n*(n-1)。
那么问题就转化为,对于每一个pair作为a,计算每一种距离的pair的个数,然后再把总和相加就是答案。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
if (points.size() < 3) {
return 0;
}
int res = 0;
for (int i = 0; i < points.size(); ++i) {
unordered_map<int, int> map;
for (int j = 0; j < points.size(); ++j) {
if (i == j) {
continue;
}
int x = points[i].first - points[j].first;
int y = points[i].second - points[j].second;
++map[x * x + y * y];
}
for (auto iter = map.begin(); iter != map.end(); ++iter) {
res += iter->second * (iter->second - 1);
}
}
return res;
}
};

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public int numberOfBoomerangs(int[][] points) {
if (points == null || points.length == 0) {
return 0;
}
if (points[0] == null || points[0].length == 0) {
return 0;
}
int res = 0;
// Do the calculation
for (int i = 0; i < points.length; i++) {
HashMap<Integer, Integer> map = new HashMap<>(); // record the count of each distance between two points
for (int j = 0; j < points.length; j++) {
if (i == j) continue;
int x = points[i][0] - points[j][0];
int y = points[i][1] - points[j][1];
int dist = x * x + y * y;
map.put(dist, map.getOrDefault(dist, 0) + 1);
}
for (int key : map.keySet()) {
res += map.get(key) * (map.get(key) - 1);
}
}
return res;
}
}