问题描述:Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:这道题首先明确,如何确定在同一条直线上?那如果固定一个点,那就是通过某点与该点的向量决定,如果向量一样,那代表同一条直线。但是向量是由(x,y)决定,但是这个值不能用作hashmap的key,所以退而使用斜率。其中斜率要注意x = 0的情况,即将vertical的数单独计算。
同时还有一个问题是重复的问题,之前的思路是如果重复,那就给通过该节点向量中的每个向量的计数+1,但是这样带来了一些问题,当新添加向量时,然后确定计数值。
后来为了简单起见,当出现重复的时候,直接将一个duplicate值更新。然后当处理完所有的节点之后,再对所有的向量值进行一次遍历,然后将value+dulplicate与max比较,并对max更新。
代码如下:324ms
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public int maxPoints(Point[] points) {
int length = points.length;
if(length<=2)
return length;
int max = 2;
HashMap<Double,Integer> maps = new HashMap<>();
for(int i = 0;i<length;i++){
maps.clear();
Point now = points[i];
int dulplicate = 1;
int vertical = 0;
for(int j = i+1;j<length;j++){
Point cmp = points[j];
if(now.x == cmp.x && now.y == cmp.y)
dulplicate++;
else if(now.x==cmp.x){
vertical++;
}else{
double slope = (cmp.y==now.y)?0.0:(1.0)*(cmp.y-now.y)/(cmp.x-now.x);
if(maps.containsKey(slope)){
maps.put(slope,maps.get(slope)+1);
}else
maps.put(slope,1);
}
}
//遍历hashmap
Iterator iterator = maps.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
int value = (int)entry.getValue();
if(value+dulplicate>max)
max = value+dulplicate;
}
max = Math.max(vertical+dulplicate,max);
}
return max;
}
}