Leetcode 1232. Check If It Is a Straight Line

博主Tyan分享了如何使用Python分别通过斜率式(Version1)和两点式(Version2)检查一组坐标是否表示一条直线的解决方案。他详细解释了两种方法的实现,并给出了LeetCode问题的参考链接。
摘要由CSDN通过智能技术生成

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Check If It Is a Straight Line

2. Solution

解析:直线的表示,可以用斜率式,也可以用两点式,Version 1是斜率式,Version 2是两点式。

  • Version 1
class Solution:
    def checkStraightLine(self, coordinates):
        diff_x = coordinates[-1][0] - coordinates[0][0]
        if diff_x == 0:
            for i in range(len(coordinates)):
                if coordinates[i][0] != coordinates[0][0]:
                    return False
            return True

        slope = (coordinates[-1][1] - coordinates[0][1]) / diff_x
        for i in range(len(coordinates) - 1):
            point1 = coordinates[i]
            point2 = coordinates[i + 1]
            if point2[0] - point1[0] == 0:
                return False
            ratio = (point2[1] - point1[1]) / (point2[0] - point1[0])
            if slope != ratio:
                return False

        return True
  • Version 2
class Solution:
    def checkStraightLine(self, coordinates):
        x1 = coordinates[0][0]
        y1 = coordinates[0][0]
        x2 = coordinates[-1][0]
        y2 = coordinates[-1][0]

        for i in range(1, len(coordinates) - 1):
            x = coordinates[i][0]
            y = coordinates[i][1]
            if (y - y1)(x2 - x1) != (x - x1)(y2 - y1):
                return False

        return True

Reference

  1. https://leetcode.com/problems/check-if-it-is-a-straight-line/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值