Lint_Code_最多有多少个点在一条直线上

来源:互联网 发布:4k网络机顶盒排名前十 编辑:程序博客网 时间:2024/05/02 01:04

问题描述:

给出二维平面上的n个点,求最多有多少点在同一条直线上。

样例:给出4个点:(1, 2)(3, 6)(0, 0)(1, 3)一条直线上的点最多有3个。

算法思想:点和点在不在一条直线上,关键两点之间的斜率是否相同。开始自己写了一些,但过于理想化,且复杂,没有考虑全面,并且没有考虑到使用map集合。最后这种还是从从网上百度出来的:

    public int maxPoints(Point[] points) {                if(points==null||points.length==0){            return 0;        }                int max=1;        //用到了map集合        HashMap<Double,Integer> map=new HashMap<Double,Integer>();                for(int i=0;i<points.length;i++){            map.clear();                       map.put((double)Integer.MIN_VALUE, 1);                        int dou=0;                        for(int j=i+1;j<points.length;j++){                if(points[j].x==points[i].x&&points[j].y==points[i].y){                    dou++;                }else{                    double key=(points[j].x-points[i].x==0?(double)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()){                if((temp+dou)>max){                    max=temp+dou;                }            }                    }        return max;    }



0 0
原创粉丝点击