ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-10-03 07:31:07  阅读:212  来源: 互联网

标签:直线 1232 Straight 成线 coordinates https line com straight



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

标签:直线,1232,Straight,成线,coordinates,https,line,com,straight
来源: https://www.cnblogs.com/grandyang/p/15363366.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有