1232. Check If It Is a Straight Line

You are given an array coordinatescoordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

Example 1:

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

Constraints:

  • 2 <= coordinates.length <= 1000
  • coordinates[i].length == 2
  • -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
  • coordinates contains no duplicate point.

这道题给了一堆二维坐标上的点,问这些点是否在一条直线上。初中的时候应该就学过两点确定一条直线,同时还有如何判断三点共线的问题,本质上就是判断三点中任意两个点组成的直线的斜率是否相同。计算两个点组成的直线的斜率,就是二者的纵坐标之差除以横坐标之差,但用除法的话就存在一个除数为0的问题,所以在比较两条直线的斜率是否相等时,将其变为乘法的形式,能有效的避免除数为0的情况。这道题说了给定的点的个数至少有两个,则可以用前两个点来确定一条直线,然后从第三个点开始遍历,判断每个遍历到的点和前两个点是否共线,就是不停的在验证三点共线问题,若某个点不在直线上,则返回 false,否则最后返回 true 即可,参见代码如下:

class Solution {
public:
    bool checkStraightLine(vector<vector<int>>& coordinates) {
        int x1 = coordinates[0][0], y1 = coordinates[0][1];
        int x2 = coordinates[1][0], y2 = coordinates[1][1];
        for (int i = 2; i < coordinates.size(); ++i) {
            int x3 = coordinates[i][0], y3 = coordinates[i][1];
            if ((x2 - x1) * (y3 - y1) != (y2 - y1) * (x3 - x1)) return false;
        }
        return true;
    }
};

Github 同步地址:

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

参考资料:

https://leetcode.com/problems/check-if-it-is-a-straight-line/

https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/408984/JavaPython-3-check-slopes-short-code-w-explanation-and-analysis.

https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/620096/Java-Python3-CPP-or-Simple-code-with-explanation-or-100-fast-or-O(1)-space

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

喜欢请点赞,疼爱请打赏❤️.

微信打赏

|

Venmo 打赏


—|—


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

×

Help us with donation