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);
    }
}
阅读更多
文章标签: 穷举
个人分类: LeetCode coding
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭