1232. 缀点成线
在一个 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
- -104 <= coordinates[i][0], coordinates[i][1] <= 104
- coordinates 中不含重复的点
方法一:
解题思路
- 斜率相等代表在一条直线上。
- 假设三个点 [x0, y0], [x1, y1], [x2, y2],有 (y1 - y0) / (x1 - x0) = (y2 - y1) / (x2 - x1),说明三个点在一条直线上。
- 当然,除法可能遇到除 0 异常,所以把除法改为乘法 (y1 - y0) × (x2 - x1) = (y2 - y1) × (x1 - x0) 。
参考代码
public boolean checkStraightLine(int[][] coordinates) {
for (int i = 2; i < coordinates.length; i++) {
int a = coordinates[i - 1][1] - coordinates[i - 2][1];
int b = coordinates[i - 1][0] - coordinates[i - 2][0];
int c = coordinates[i][1] - coordinates[i - 1][1];
int d = coordinates[i][0] - coordinates[i - 1][0];
if (a * d != b * c) {
return false;
}
}
return true;
}
执行结果