Leetcode 1232. Check If It Is a Straight Line

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

1. Description

Check If It Is a Straight Line

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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/
如果有收获,可以请我喝杯咖啡!