[LeetCode] 1037. Valid Boomerang 有效的回旋镖


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

这道题定义了一种回旋镖就是不在同一条直线上的三个点,现在给了同一平面上的三个点,让判断能否组成一个回旋镖。实际上就是初中的几何问题,判断三点是否共线,忘记了的话估计不太容易做出来,虽然只是道 Easy 的题目。我们都知道两点能确定一条直线,那么对于三个点 p1,p2,和 p3,只要 p1 和 p2 连接而成的直线和 p1 和 p3 连接而成的直线重合,则表示三点共线。如何判断直线重合呢,最简单的方法就是看斜率是否相等,知道了两个点求斜率也很简单,只要满足 (y3 - y1) / (x3 - x1) = (y2 - y1) / (x2 - x1),就表示三点共线,换成乘法形式的就是 (y3 - y1) * (x2 - x1) = (y2 - y1) * (x3 - x1),而题目中说的回旋镖就是三点不共线的情况,将这里的等号换成不等号即可,一行搞定碉堡了,参见代码如下:


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

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1037


参考资料:

https://leetcode.com/problems/valid-boomerang/

https://leetcode.com/problems/valid-boomerang/discuss/286702/JavaC%2B%2BPython-Straight-Forward


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2021-02-20 14:45  Grandyang  阅读(372)  评论(0编辑  收藏  举报
Fork me on GitHub