缀点成线Java
文章发布较早,内容可能过时,阅读注意甄别。
# 题目
给定一个数组 coordinates ,其中 coordinates[i] = [x, y] , [x, y] 表示横坐标为 x、纵坐标为 y 的点。请你来判断,这些点是否在该坐标系中属于同一条直线上。
示例 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 中不含重复的点
# 思路
// 线性回归是吧,判断有没有这样一个方程f(x)=kx+b,使得所有点都在线上
// 注意直线与y轴平行的情况
# 解法
class Solution {
// 线性回归是吧,判断有没有这样一个方程f(x)=kx+b,使得所有点都在线上
// 注意直线与y轴平行的情况
public boolean checkStraightLine(int[][] coordinates) {
int [] one=coordinates[0];
int [] two=coordinates[1];
double k=(one[0]==two[0])?(double)Integer.MAX_VALUE:(one[1]-two[1]-0.0)/(one[0]-two[0]);
System.out.println(k);
double b=one[1]-k*one[0];
int n=coordinates.length;
if(k==Integer.MAX_VALUE){
int x=one[0];
for(int i=0;i<n;i++){
if(coordinates[i][0]!=x) return false;
}
return true;
}
for(int i=0;i<n;i++){
int y=coordinates[i][1];
int x=coordinates[i][0];
if(y!=k*x+b) return false;
}
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 总结
- 分析出几种情况,然后分别对各个情况实现


