LeetCode 1232. 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.

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.

解题思路

  题目大意:二维平面给定任意数量(大于2)的点的坐标,判断这些点是不是位于同一条直线上。

  这是一道十分简单的题目,有基本的数学基础的都可以做出来。选定一个基准点,然后依次遍历剩下的点,看看是不是斜率的绝对值都相同即可。为了更加方便地去计算,同时避免考虑斜率正负的问题,这里采用方向向量的方式进行计算。任意选择两个点,并选择其中的一个作为基准点,计算他们之间的方向向量。然后依次遍历剩下的点,计算基准点和其之间的方向向量,只要二者方向相同或相反就说明他们位于一条直线上。

  Python代码如下:

class Solution:
    def checkStraightLine(self, coordinates) -> bool:
        if len(coordinates) <= 2:
            return True
        # Direction Vector
        base = [coordinates[0][0] - coordinates[1][0], coordinates[0][1] - coordinates[1][1]]

        for i in range(2, len(coordinates)):
            v = [coordinates[0][0] - coordinates[i][0], coordinates[0][1] - coordinates[i][1]]
            if v[0] * base[1] != v[0] * base[0]:
                return False
        return True

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值