要求
回旋镖定义为一组三个点,这些点各不相同且不在一条直线上。
给出平面上三个点组成的列表,判断这些点是否可以构成回旋镖。
示例 1:
输入:[[1,1],[2,3],[3,2]]
输出:true
示例 2:
输入:[[1,1],[2,2],[3,3]]
输出:false
核心代码
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
if points[0] == points[1] or points[1] == points[2] or points[2] == points[0]:
return False
x0,x1,x2 = points[0][0],points[1][0],points[2][0]
y0,y1,y2 = points[0][1],points[1][1],points[2][1]
if x0 == x1 or x2 == x1:
return x0 != x2
return abs(1.0 * (y2 - y1)/(x2 - x1) - 1.0 * (y1 - y0)/(x1 - x0)) > 0.0001
另一解法
class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x1,x2,x3 = points[0][0],points[1][0],points[2][0]
y1,y2,y3 = points[0][1],points[1][1],points[2][1]
return (x1 * y2 - x2 * y1) + (x2 * y3 - x3 * y2) + (x3 * y1 - x1 * y3) != 0
解题思路:第一种方式:我们使用数学的方法,当三点不在统一直线的时候,我们使用斜率不相等的方式来完成;第二种解法:题目其实问的就是三点组成的三角形的面积不能为0,因为当有任意两点或三点相同时,三点构成一条线,不满足要求,只有当三点都不相同,并且三点不共线,三点构成的三角形的面积一定 > 0,比较好的思想。