LeetCode 题解工作台

有效的回旋镖

给定一个数组 points ,其中 points[i] = [x i , y i ] 表示 X-Y 平面上的一个点, 如果这些点构成一个 回旋镖 则返回 true 。 回旋镖 定义为一组三个点,这些点 各不相同 且 不在一条直线上 。 示例 1: 输入: points = [[1,1],[2,3],…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

设三点分别为 , , 。两点之间斜率计算公式为 。 要使得三点不共线,需要满足 ,我们将式子变形得到 $(y_2-y_1)*(x_3-x_2) \neq (y_3-y_2)*(x_2-x_1)$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个数组 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 == 3
  • points[i].length == 2
  • 0 <= xi, yi <= 100
lightbulb

解题思路

方法一:斜率比较

设三点分别为 (x1,y1)(x_1,y_1), (x2,y2)(x_2,y_2), (x3,y3)(x_3,y_3)。两点之间斜率计算公式为 y2y1x2x1\frac{y_2-y_1}{x_2-x_1}

要使得三点不共线,需要满足 y2y1x2x1y3y2x3x2\frac{y_2-y_1}{x_2-x_1}\neq\frac{y_3-y_2}{x_3-x_2},我们将式子变形得到 (y2y1)(x3x2)(y3y2)(x2x1)(y_2-y_1)*(x_3-x_2) \neq (y_3-y_2)*(x_2-x_1)

注意:

  1. 当两点之间斜率不存在,即 x1=x2x_1=x_2,上述变式仍然成立;
  2. 若斜率除法运算比较存在精度问题,同样可以变换为乘法。

时间复杂度 O(1)O(1)

1
2
3
4
5
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)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

有效的回旋镖题解:数组·数学 | LeetCode #1037 简单