Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.


题意:给一个二维平面,上面有好多点,有横纵坐标,找出一条直线,使得这条线上的点数量最多。

这是当时百度春招实习时面试官问过的一道题,当时虽然没有写代码。但是之后回来也没有再看过。今天刷题,突然发现是LeetCode原题,hard难度。不仅感慨,长叹一声。然后今天舍友视频面试小红书的时候也被问到了这道题。所以就做一下记录吧。


思路的话就是:一般就是求斜率,遍历所有的点,但是有几个地方需要注意一些,因为这些点可能有重合的!!!还有就是求斜率的时候注意垂直X轴的那些点,斜率是无穷,单独计算。

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
28
29
30
31
32
33
34
35
36
37
38
39
40
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++){
         //针对每个点,用hash表存储和其他点所能组成的各种斜率情况,求一个最大
             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++;
                     }
                     ///垂直X轴的点们
                     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);
                     double  k = ( double )(points[j].x - points[i].x) / ( double )(points[j].y - points[i].y);
                     ///存在的话直接加1
                     if (hm.containsKey(k)){
                         hm.put(k,hm.get(k) +  1 );
                     } else {
                         hm.put(k,  2 ); ////包含当前点,和遍历到的点
                     }
                     //每次都求一个最大值,求每个不同斜率的最大值
                     result = Math.max(result, hm.get(k) + samep);
                 }
             }
             ///每次需要比较一下在一条直线,垂直X轴上的点。。。
             result = Math.max(result, samex);
         }
         return  result;
     }
}