题目
https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/
思路
我的代码思路,设y=ax+b,不咋好。
官方题解:为方便后续计算,将所有点向 (-P0x, -P0y)方向平移。平移后的p0’在坐标原点O上。
直线过原点,故设其方程为 Ax+By=0。
代码
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int len=coordinates.length;
if(len==0||len==1||len==2)
return true;
int x0=coordinates[0][0];
int y0=coordinates[0][1];
int x1=coordinates[1][0];
int y1=coordinates[1][1];
int flag=0;
if(x1-x0==0){
flag=1;
}
double a=(y1-y0)*1.0/(x1-x0);
double b=y1-a*x1;
for(int i=1;i<len;i++){
int[] cp=coordinates[i];
int x=cp[0];
int y=cp[1];
if(flag==1){
if(x!=x1)
return false;
}
else{
if((a*x+b)!=y)
return false;
}
}
return true;
}
}
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int deltaX = coordinates[0][0], deltaY = coordinates[0][1];
int n = coordinates.length;
for (int i = 0; i < n; i++) {
coordinates[i][0] -= deltaX;
coordinates[i][1] -= deltaY;
}
int A = coordinates[1][1], B = -coordinates[1][0];
for (int i = 2; i < n; i++) {
int x = coordinates[i][0], y = coordinates[i][1];
if (A * x + B * y != 0) {
return false;
}
}
return true;
}
}