LeetCode 题解工作台
有效的回旋镖
给定一个数组 points ,其中 points[i] = [x i , y i ] 表示 X-Y 平面上的一个点, 如果这些点构成一个 回旋镖 则返回 true 。 回旋镖 定义为一组三个点,这些点 各不相同 且 不在一条直线上 。 示例 1: 输入: points = [[1,1],[2,3],…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
设三点分别为 , , 。两点之间斜率计算公式为 。 要使得三点不共线,需要满足 ,我们将式子变形得到 $(y_2-y_1)*(x_3-x_2) \neq (y_3-y_2)*(x_2-x_1)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给定一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点,如果这些点构成一个 回旋镖 则返回 true 。
回旋镖 定义为一组三个点,这些点 各不相同 且 不在一条直线上 。
示例 1:
输入:points = [[1,1],[2,3],[3,2]] 输出:true
示例 2:
输入:points = [[1,1],[2,2],[3,3]] 输出:false
提示:
points.length == 3points[i].length == 20 <= xi, yi <= 100
解题思路
方法一:斜率比较
设三点分别为 , , 。两点之间斜率计算公式为 。
要使得三点不共线,需要满足 ,我们将式子变形得到 。
注意:
- 当两点之间斜率不存在,即 ,上述变式仍然成立;
- 若斜率除法运算比较存在精度问题,同样可以变换为乘法。
时间复杂度 。
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
(x1, y1), (x2, y2), (x3, y3) = points
return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for efficient use of mathematical properties to solve the problem.
- question_mark
Expect the candidate to explain collinearity and how the area of a triangle can help determine this.
- question_mark
Candidates should confirm that all points are distinct before proceeding with further checks.
常见陷阱
外企场景- error
Confusing collinearity check with simple distance calculations, which do not guarantee non-collinearity.
- error
Overlooking the distinctness of the points, leading to incorrect conclusions about the boomerang formation.
- error
Not understanding how the area formula directly applies to this problem for determining valid boomerangs.
进阶变体
外企场景- arrow_right_alt
Handling higher dimensions if the problem was extended to more than 2D.
- arrow_right_alt
Checking for a set of points beyond three, such as determining if any subset forms a boomerang.
- arrow_right_alt
Adapting the solution for larger inputs or multiple sets of points.