5月挑战Day8-Check If It Is a Straight Line(easy)

Day8-Check If It Is a Straight Line

问题描述:

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.

给一系列坐标,检查这些坐标连成的线是否能形成一条直线。

解法:

点在同一条直线上的意思就是斜率是同一的,为此最简单的做法就是先取出前两个点算一下斜率 ,然后遍历剩下的点看斜率是否相同就可以了,这里需要注意的就是当两个点的X坐标相同时的情况,这种情况是不存在斜率的概念的需要另外考虑。

class Solution:
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        if len(coordinates) < 2:
            return False
        delta_x,delta_y = coordinates[1][0] - coordinates[0][0],coordinates[1][1] - coordinates[0][1]
        
        if delta_x == 0:
            for i in range(len(coordinates) - 1):
                if coordinates[i][0] != coordinates[i + 1][0]:
                    return False
            return True
        delta = delta_y / delta_x

        for i in range(1,len(coordinates) - 1):
            temp_x,temp_y = coordinates[i+1][0] - coordinates[i][0],coordinates[i+1][1] - coordinates[i][1]
            if temp_x == 0:
                return False
            temp_delta = temp_y / temp_x
            
            if temp_delta != delta:
                return False
        return True

时间复杂度为O(n),空间复杂度为O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值