文章作者:Tyan 博客:noahsnail.com | CSDN | 简书
1. Description
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
- https://leetcode.com/problems/check-if-it-is-a-straight-line/