1232. 缀点成线 - 力扣(LeetCode)

可以使用数学方法来判断这些点是否在同一条直线上。

方法:

如果所有点在同一条直线上,则任意两点之间的斜率应该相同。斜率的计算公式为:

\text{Slope} = \frac{y_2 - y_1}{x_2 - x_1}

由于浮点数计算可能引起精度问题,我们可以使用交叉相乘来避免:

(y_2 - y_1) \times (x_3 - x_1) = (y_3 - y_1) \times (x_2 - x_1)

只要对于所有点都满足这个关系式,就说明它们在同一直线上。

代码实现:

def checkStraightLine(coordinates):
    # 取前两个点计算基准斜率
    x0, y0 = coordinates[0]
    x1, y1 = coordinates[1]
    
    # 遍历剩下的点,验证斜率是否相同
    for i in range(2, len(coordinates)):
        x, y = coordinates[i]
        if (y1 - y0) * (x - x0) != (y - y0) * (x1 - x0):
            return False
    return True

# 测试用例
coordinates = [[1,2], [2,3], [3,4], [4,5], [5,6]]
print(checkStraightLine(coordinates))  # 输出: True

coordinates = [[1,1], [2,2], [3,4], [4,5]]
print(checkStraightLine(coordinates))  # 输出: False

复杂度分析:

  • 该方法的时间复杂度为 O(n),因为我们只需要遍历所有点一次。

  • 空间复杂度为 O(1),因为我们只使用了常数级别的额外空间。

这样,我们可以高效地判断给定的点是否共线。

更多推荐