[LeetCode]Maximum number of points on a straight line in 2d plane

本文介绍了一种解决几何问题的方法:如何找出平面上给定点集中最大数量的共线点。通过计算每两点间的斜率并利用哈希映射记录出现次数最多的斜率来确定最长的共线点集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From Here

Solution:

Remember that a line can be represented by y=kx+d, if p1 and p2 are in same line, then y1=x1k+d, y2=kx2+d, so y2-y1=kx2-kx1, so k=(y2-y1)/(x2-x1), then we can apply this formula to check if two points are in same line, however how to handle the duplicate points problem?

So instead to calculate the line with maximum points , we should calculate longest line(maximum ponts) through same point,

public class Solution {
     public  int maxPoints(Point[] points) {

            if (points==null||points.length==0){
                return 0;
            }  
            //slope -> number of points
            HashMap<Double, Integer> map=new HashMap<Double, Integer>();;
            int max=1;

            for(int i=0; i<points.length; i++){
                // current point changed, clear map for this point
                map.clear();

                // maybe all points contained in the list are same points
                // ,and same points' k is represented by Integer.MIN_VALUE
                map.put((double)Integer.MIN_VALUE, 1);

                int dup=0;

                for(int j=i+1; j<points.length; j++){
                   if (points[j].x==points[i].x&&points[j].y==points[i].y){
                       dup++;
                       continue;
                   }

                   // 1) look 0.0+(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x)
                   // because (double)0/-1 is -0.0, so we should use 0.0+-0.0=0.0 to solve 0.0 !=-0.0 problem

                   // 2) if the line through two points are parallel to y coordinator, then K(slop) is Integer.MAX_VALUE
                   double key=points[j].x-points[i].x==0?Integer.MAX_VALUE:0.0+(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);

                   if (map.containsKey(key)){
                       map.put(key, map.get(key)+1);
                   }
                   else{
                      map.put(key, 2);
                   }
               }

              for (int temp: map.values()){
                  // duplicate may exist
                  //all duplicate of the cur point are on the same line
                  max = Math.max(max, temp+dup);
              }
            }
            return max;
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值