题目描述:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
求二维平面上n个点中,最多共线的点数。
思路解析:
遍历两层循环:第一层循环代表起始点,第二层循环代表第二个点,两点定线
特殊情况:
- 点为空,长度为0,return 0
- 只有两个点,return 2
- 外层循环外面定义最大值max初始化为1,用来表示点的个数。因为非空,所以长度至少为1.
在外层循环里面
- 需要定义每次的最大值,即与点 i 共线的最大值,还有重合的点的个数same。
- 如果两点重合,same就加1,same表示重合的点
- 如果斜率一样,那就共线,可以使用HashMap来存储<斜率,个数>,然后内层循环结束,就去找到最大值
- 不要忘记每次找到最大值以后就要把same加上
- 斜率是float类型,可以强制类型转换
- HashMap.values()
- HashMap.get()
- HashMap.put( , )
代码:
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.HashMap;
public class Solution {
public int maxPoints(Point[] points) {
if(points==null || points.length==0){
return 0;
}
if(points.length<=2){
return points.length;
}
int max=1;
for(int i=0;i<points.length;i++){
HashMap<Float,Integer> hm = new HashMap<Float,Integer>();
int same=0;
int localmax=1;
for(int j=0;j<points.length;j++){
if(i==j)
continue;
if(points[i].x==points[j].x && points[i].y==points[j].y){
same++;
continue;
}
float slope=((float)(points[i].y-points[j].y))/(points[i].x-points[j].x);
if(hm.containsKey(slope))
hm.put(slope,hm.get(slope)+1);
else
hm.put(slope,2);
}
for(Integer value:hm.values())
localmax = Math.max(localmax,value);
localmax+=same;
max = Math.max(max,localmax);
}
return max;
}
}