一.问题描述
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.
二.解题思路
判断点是否在一条直线上就看斜率是否一样。
注意一下斜率不存在垂直的情况。
记得leetcode好像有一道类似的题,不记得题号了。
时间复杂度:O(n)
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac。
三.源码
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
if len(coordinates)==2:return True
if coordinates[0][0]!=coordinates[1][0]:
k=(coordinates[1][1]-coordinates[0][1])/(coordinates[1][0]-coordinates[0][0])
else:k=float('inf')
for i in range(2,len(coordinates)):
temp=0
if coordinates[i][0]!=coordinates[i-1][0]:
temp=(coordinates[i][1]-coordinates[i-1][1])/(coordinates[i][0]-coordinates[i-1][0])
else:temp=float('inf')
if temp!=k:return False
return True