在一个 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 中不含重复的点
go语言
// 两点 A(x0, y0) B(x1, y1) 确定一条直线, 直线的斜率为 k = (y1 - y0) / (x1 - x0)
// 所以我们只要遍历数组,判断当前点和上个点构成的直线的斜率是否和之前相同即可。
// 用交叉相乘判断相等即可
func checkStraightLine(coordinates [][]int) bool {
c := coordinates
x, y := c[1][0] - c[0][0], c[1][1] - c[0][1]
for i := 2; i < len(c); i++ {
x1, y1 := c[i][0] - c[i-1][0], c[i][1] - c[i-1][1]
if x1 * y != x * y1 {
return false
}
}
return true
}