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)。
217

被折叠的 条评论
为什么被折叠?



