LeetCode(149)-Max Points on a Line 共线点个数

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
求最大的共线点的个数

public class l149_maxpoints_in_line {
    static class Point{
        int x;
        int y;
        Point(){x=0;y=0;};
        Point(int x,int y){
            this.x=x;
            this.y=y;
        }
    }

    int maxPoints(Point[] points) {
       int len=points.length;
       if(len<2) return  len;
       int res=0;
       for(int i=0;i<len;i++){
           int duplicate=1;
           int vertival=0;
           Map<Float,Integer> map=new HashMap<>();
           Point a=points[i];
           for (int j=0;j<len;j++) {
               if (i == j) continue;
               Point b = points[j];
               //重合点
               if (a.x == b.x) {
                   if (a.y == b.y) {
                       duplicate++;
                       else
  //不存在斜率
                    {
                       vertival++;
                   }
               } else {
                   float k = (float) (b.y - a.y) / (b.x - a.x);
                   if (map.get(k) == null) {
                       map.put(k, 1);
                   } else {
                       map.put(k, map.get(k) + 1);
                   }
               }
           }
               int max=vertival;
               for(float k:map.keySet()){
                   max=Math.max(max,map.get(k));
               }
               res=Math.max(res,max+duplicate);

           }
           return res;
       }


    public static void main(String[] args) {
        l149_maxpoints_in_line c=new l149_maxpoints_in_line();
  //      Scanner scanner=new Scanner(System.in);
        Point[] points=new Point[9];
        points[0]=new Point(84,250);
        points[1]=new Point(0,0);
        points[2]=new Point(1,0);
        points[3]=new Point(0,-70);
        points[4]=new Point(0,-70);
        points[5]=new Point(1,-1);
        points[6]=new Point(21,10);
        points[7]=new Point(42,90);
        points[8]=new Point(-42,-230);

        int ans=c.maxPoints(points);
        System.out.println(ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值