题目原文:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
题目大意:
给出2维坐标系内的n个点,求出最多有多少个点共线。
题目分析:
对每个点,使用一个hashmap记录<斜率,点数>,这样就知道与这个点共线的点最多有多少个,然后维护最大值即可。
有几个坑,第一斜率要用double而不是int,第二有重复的点,那么该点的hashmap的所有value都+1,第三有斜率不存在的情况,用一个特殊值记录。
源码:(language:java)
public class Solution {
public int maxPoints(Point[] points) {
if(points.length <= 0) return 0;
if(points.length <= 2) return points.length;
int result = 0;
for(int i = 0; i < points.length; i++){
HashMap<Double, Integer> hm = new HashMap<Double, Integer>();
int samex = 1;
int samep = 0;
for(int j = 0; j < points.length; j++){
if(j != i){
if((points[j].x == points[i].x) && (points[j].y == points[i].y)){
samep++;
}
if(points[j].x == points[i].x){
samex++;
continue;
}
double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
if(hm.containsKey(k)){
hm.put(k,hm.get(k) + 1);
}else{
hm.put(k, 2);
}
result = Math.max(result, hm.get(k) + samep);
}
}
result = Math.max(result, samex);
}
return result;
}
}
成绩:
46ms,17.98%,27ms,7.06%
cmershen的碎碎念:
粗看还以为是传说中的计算几何,其实也是比较水的一道题,但考虑用hashmap存储斜率的思路还是不太好想到的。