题目描述:
对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
示例:

解题思路:
方法一:
斜率相同的点在同一直线上。 相同位置的点也在同一直线上。
最多能有多少个点位于同一直线上:斜率相同的点 + 相同位置的点
方法二:
循环遍历每个点,先统计其他点与当前点的重合个数dup
以及与当前点在同一条垂直线上vlt的个数(斜率不存在的情况),
再统计其他点与当前点在同一条直线的个数(斜率存在的情况),可利用HashMap统计这个点相对于其他点的不同斜率的个数,
最后比较得到最多的在同一条直线上的点个数。
代码:
//所用时间较短
import java.util.*;
/*
* public class Point {
* int x;
* int y;
* }
*/
public class Solution {
/**
*
* @param points Point类一维数组
* @return int整型
*/
public int maxPoints (Point[] points) {
// write code here
if(points == null || points.length == 0) //点的数组为空则返回0
return 0;
if(points.length <3) //若数组的长度小于3,则直接返回长度,只有两点必定在一条直线上
return points.length;
int samepoint ; //相同位置的点
int max = 2;
int sameSlopePoint; //相同斜率的点
for(int i=0;i<points.length;i++) {
samepoint = 0;
for(int j=i+1;j<points.length;j++) {
sameSlopePoint =1; //第一个点加上来
int Xdiatance = points[i].x - points[j].x; // X轴两点间的距离
int Ydiatance = points[i].y - points[j].y; // Y轴两点间的距离
if(Xdiatance == 0 && Ydiatance == 0) {
samepoint++;
}else {
sameSlopePoint = 2;
for(int k = j+1;k < points.length; k++) {
int Xdiatance2 = points[i].x - points[k].x;
int Ydiatance2 = points[i].y - points[k].y;
if(Xdiatance * Ydiatance2 == Ydiatance * Xdiatance2) {//乘法表示避免除法分母不为零的问题
sameSlopePoint++;
}
}
}
if(max < sameSlopePoint + samepoint) {
max = sameSlopePoint + samepoint;
}
}
}
return max;
}
}
//所用时间长
import java.util.*;
/*
* public class Point {
* int x;
* int y;
* }
*/
public class Solution {
/**
*
* @param points Point类一维数组
* @return int整型
*/
public int maxPoints (Point[] points) {
// write code here
int len = points.length;
if(len < 2)
return len;
int max_points = 0;
for(int i = 0; i < len; i++){
int dup = 0, vlt = 0; //重合个数,垂直个数
Point a = points[i];
Map<Float,Integer> map = new HashMap<>(); //key为斜率
for(int j = 0; j < len; j++){
if(i == j) continue;
else{
Point b = points[j];
if(a.x == b.x){
if(a.y == b.y) dup++;
else vlt++;
}
else{
float k = (float)(b.y - a.y)/(b.x - a.x);
if(map.get(k) == null) map.put(k, 1);
else map.put(k, 1 + map.get(k));
}
}
}
int max = vlt;
for(float k :map.keySet()){
max = Math.max(max, map.get(k));
}
max_points = Math.max(max_points, max + dup); //加上重复点的个数
}
return max_points + 1;
}
}
该博客探讨了在二维平面上,给定n个点的情况下,如何确定最多有多少个点可以位于同一条直线上。通过示例和解题思路,解释了这个问题的解决方法。
8019

被折叠的 条评论
为什么被折叠?



