在一个 XY 坐标系中有一些点,我们用数组 coordinates
来分别记录它们的坐标,其中 coordinates[i] = [x, y]
表示横坐标为 x
、纵坐标为 y
的点。
请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。
示例 1:
输入:coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
输出:true
示例 2:
输入:coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
输出:false
提示:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
中不含重复的点思路:
按x值从小到大排序之后比较相邻两点的斜率是不是全部相同即可。
注意除数不能为0。
时间复杂度:O(NlogN),因为排了序
空间复杂度:O(1)
class Solution(object):
def checkStraightLine(self, coordinates):
"""
:type coordinates: List[List[int]]
:rtype: bool
"""
c = sorted(coordinates, key = lambda x:x[0])
k = None
for i in range(len(c)):
if i:
x0, y0 = c[i - 1][0], c[i - 1][1]
x1, y1 = c[i][0], c[i][1]
if x0 == x1:
return False
new_k = 1.0 * (y1 - y0) / (x1 - x0)
if k and k != new_k:
return False
k = new_k
return True