[LeetCode] 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:

[LeetCode] 1232. Check If It Is a Straight Line 缀点成线

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

Example 2:

[LeetCode] 1232. Check If It Is a Straight Line 缀点成线

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 题目讲解汇总(持续更新中...)

上一篇:hashcode 和 equals


下一篇:【Linux入门】一文看懂 Linux man 手册