- 缀点成线
在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。
请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。
来源:力扣(LeetCode)
public static boolean checkStraightLine(int[][] coordinates) {
int num=coordinates.length-1;
int x=coordinates[0][0];
int y=coordinates[0][1];
if(x==coordinates[1][0]) {
while(num>1) {
if(coordinates[num][0]!=x) {
return false;
}
num--;
}
return true;
}
num=coordinates.length-1;
if(y==coordinates[1][1]) {
while(num>1) {
if(coordinates[num][1]!=y) {
return false;
}
num--;
}
return true;
}
num=coordinates.length-1;
double k=(double)(x-coordinates[1][0])
/(double)(y-coordinates[1][1]);
while(num>1) {
if((coordinates[num][0]-x)!=(coordinates[num][1]-y)*k){
return false;
}
num--;
}
return true;
}