美文网首页
LeetCode 1232. Check If It Is a

LeetCode 1232. Check If It Is a

作者: LiNGYu_NiverSe | 来源:发表于2020-11-25 01:24 被阅读0次

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。

相关文章

网友评论

      本文标题:LeetCode 1232. Check If It Is a

      本文链接:https://www.haomeiwen.com/subject/aqrgiktx.html