问题描述
- 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]]
问题分析
- 暴力法: 三层遍历,得到 i ,j, k三个点,然后统计相应的符合规定的次数。但是注意,题目给出的数据规模 N = 500 , 上述 O(N^3) 的时间复杂度肯定会超时。
- 给定数据规模为
N = 500
,那么肯定是要设计一个 低于 O(N^3) 的算法的。 - 正确做法: 遍历每一个点,然后计算其他点到该点的距离,用 map 存储关于这个点的距离信息。key 存储到该点的 distance, value 存储到该点距离为 distance 的有多少个点。 然后再遍历map中的 values,累加所有个数。如到该点距离为2的点有3个,那么可以得出
3 * 2 = 6
种符合要求的组合。 - 但有一个陷阱需要注意,那便是距离的计算
- 因为我们不需要精确的距离,只要一种相对的概念,等于或者不等于,所以我们统计距离的平方即可。
如果统计的是精确地距离,可以会带来以下麻烦:
- 浮点数精度损耗问题
- 开根号带来额外的开销
- 因为我们不需要精确的距离,只要一种相对的概念,等于或者不等于,所以我们统计距离的平方即可。
- 计算距离平方时,同样也要注意数据规模,因为有可能数据溢出,该题根据题意,最大距离不超过 int 取值范围,所以可以用 int 存储。
- 时间复杂度:O(N^2)
经验教训
- 当使用查找表 map时,如何灵活选取键值 key,让问题更加方便
- 距离计算中的浮点数精度损失问题 以及 数据溢出问题
- 进阶题目: Leetcode 149-Max Points on a Line
代码实现
class Solution {
public int numberOfBoomerangs(int[][] points) {
if (points == null || points.length == 0 || points[0] == null || points[0].length == 0) {
return 0;
}
int res = 0;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < points.length; i++) {
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
int dis = getDistance(points[i], points[j]);
map.put(dis, map.getOrDefault(dis, 0) + 1);
}
// 注意如何遍历map中的values
for (int count : map.values()) {
res += count * (count - 1);
}
map.clear();
}
return res;
}
public int getDistance(int[] p1, int[] p2) {
return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);
}
}