1037. Valid Boomerang

1037. Valid Boomerang

A boomerang is a set of 3 points that are all distinct and not in a straight line.

Given a list of three points in the plane, return whether these points are a boomerang.

Example 1:

Input: [[1,1],[2,3],[3,2]]
Output: true

Example 2:

Input: [[1,1],[2,2],[3,3]]
Output: false

Note:
1.points.length == 3
2.points[i].length == 2

3.0 <= points[i][j] <= 100

思路

拿到题目先画图

我们来理解题意,首先回旋镖的意思见 回旋镖

根据题意,三个点组成两条直线,两条直线需要有一定的夹角,能组成三角形就满足条件。

那反过来,如果两条直线斜率相同,那就不能组成三角形。

解法:

斜率 k = (y2-y1) / (x2-x1)

伪代码:

return K(AB) != K(BC)

代码:

return (points[1][1]-points[0][1]) / (points[1][0]-points[0][0]) != (points[2][1]-points[1][1]) / (points[2][0]-points[1][0]);

注意算斜率是除法,我们需要考虑除0的情况。两边同时乘以两个除数,把除法转换为乘法。

C++

class Solution {
public:
bool isBoomerang(vector<vector<int>>& points) {
return (points[1][1]-points[0][1]) * (points[2][0]-points[1][0]) != (points[2][1]-points[1][1]) * (points[1][0]-points[0][0]);
}
};

Rust

impl Solution {
pub fn is_boomerang(points: Vec<Vec<i32>>) -> bool {
return (points[1][1]-points[0][1]) * (points[2][0]-points[1][0]) != (points[2][1]-points[1][1]) * (points[1][0]-points[0][0]);
}
}

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 注销 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 注销 /  更改 )

Connecting to %s