LeetCode 1232. Check If It Is a Straight Line 检查是否为直线 (Easy))

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
给您一个数组坐标,coordinates [i] = [x,y],其中[x,y]代表一个点的坐标。检查这些点是否在XY平面上成直线

Example 1:

Example 1

Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
输入:坐标= [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
输出:

Example 2:

Example 2

Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
输入:坐标= [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
输出:

Constraints:

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

Solution:

class Solution:
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        if len(coordinates) == 2:
            return True
        x1, y1 = coordinates[0]
        x2, y2 = coordinates[1]
        
        for c in coordinates[2:]:
            x, y = c
            if (y2 - y1) * (x - x1) != (x2 - x1) * (y - y1):
                return False            
        return True
            

We can use cross product to check collinearity.
cross product of 2d vectors = x1y2 - x2y1
if they are collinear, the cross product is 0.
So we can check if x1y2 == x2y1 .
我们可以使用叉积检查共线性。
2d向量的叉积 = x1y2 - x2y1
如果它们是共线的,则叉积为0。
因此,我们可以检查是否 x1y2 == x2y1。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容