LeetCode 题解工作台
回旋镖的数量
给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [x i , y i ] 。 回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的欧式距离和 i 和 k 之间的欧式距离相等( 需要考虑元组的顺序 )。 返回平面上所有回旋镖的数量。 示例 1: …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以枚举 `points` 中的每个点作为回旋镖的点 ,然后用一个哈希表 记录其他点到 的距离出现的次数。 如果有 个点到 的距离相等,那么我们可以任选其中 个点作为回旋镖的 和 ,方案数为 $A_x^2 = x \times (x - 1)$。因此,我们对哈希表中的每个值 ,都计算并累加 ,就可以得到满足题目要求的回旋镖数量之和。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的欧式距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。
返回平面上所有回旋镖的数量。
示例 1:
输入:points = [[0,0],[1,0],[2,0]] 输出:2 解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
示例 2:
输入:points = [[1,1],[2,2],[3,3]] 输出:2
示例 3:
输入:points = [[1,1]] 输出:0
提示:
n == points.length1 <= n <= 500points[i].length == 2-104 <= xi, yi <= 104- 所有点都 互不相同
解题思路
方法一:枚举 + 计数
我们可以枚举 points 中的每个点作为回旋镖的点 ,然后用一个哈希表 记录其他点到 的距离出现的次数。
如果有 个点到 的距离相等,那么我们可以任选其中 个点作为回旋镖的 和 ,方案数为 。因此,我们对哈希表中的每个值 ,都计算并累加 ,就可以得到满足题目要求的回旋镖数量之和。
时间复杂度 ,空间复杂度 。其中 是数组 points 的长度。
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0
for p1 in points:
cnt = Counter()
for p2 in points:
d = dist(p1, p2)
ans += cnt[d]
cnt[d] += 1
return ans << 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) because each point is used as a pivot and distances are computed to all other points. Space complexity is O(n) for the hash map storing distances per pivot point. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They may hint at optimizing distance calculations using squared distances instead of square roots.
- question_mark
Expect clarifying questions about handling duplicate distances efficiently with hash maps.
- question_mark
They may ask about edge cases such as a single point or collinear points where boomerangs are limited.
常见陷阱
外企场景- error
Calculating Euclidean distance with square roots can introduce floating point errors; always use squared distance.
- error
Failing to multiply frequency by (frequency - 1) for ordering of tuples will give incorrect counts.
- error
Resetting the hash map incorrectly between pivot points can mix distances and produce wrong totals.
进阶变体
外企场景- arrow_right_alt
Counting boomerangs in 3D points instead of 2D using the same array scanning plus hash lookup pattern.
- arrow_right_alt
Finding boomerangs where distances satisfy a specific ratio rather than equality.
- arrow_right_alt
Modifying the problem to return all boomerang tuples explicitly instead of just the count.