Description
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.
分析
题目的意思是:给你一个数组里面的数对是否在同一条直线上,最直观的判断方法是斜率,但是斜率可能会出现分母为0的情况,需要单独来处理,后面发现可以直接比较x1y2==x2y1就行了。这里的x和y是两数的两点的差值,具体过程看代码,也比较简单。
代码
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
d={}
n=len(coordinates)
x1=coordinates[1][0]-coordinates[0][0]
y1=coordinates[1][1]-coordinates[0][1]
for i in range(2,n,1):
x2=coordinates[i][0]-coordinates[i-1][0]
y2=coordinates[i][1]-coordinates[i-1][1]
if(x1*y2!= x2*y1):
return False
return True