149. Max Points on a Line

Posted 鸵鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了149. Max Points on a Line相关的知识,希望对你有一定的参考价值。

class Solution {
    public int maxPoints(Point[] points) {
        if(points.length<3)
            return points.length;
        int res=0;
        Map<Integer, Map<Integer,Integer>> map=new HashMap<Integer, Map<Integer, Integer>>();
        for(int i=0;i<points.length;i++)
        {
            map.clear();
            int samepoint=1,max=0;
            for(int j=i+1;j<points.length;j++)
            {
                int x=points[i].x-points[j].x;
                int y=points[i].y-points[j].y;
                if(x==0&&y==0)
                    samepoint++;
                else
                {
                    int d=gcd(x,y);
                    x/=d;
                    y/=d;
        			if (map.containsKey(x)){
        				if (map.get(x).containsKey(y)){
        					map.get(x).put(y, map.get(x).get(y)+1);
        				}else{
        					map.get(x).put(y, 1);
        				}   					
        			}else{
        				Map<Integer,Integer> m = new HashMap<Integer,Integer>();
        				m.put(y, 1);
        				map.put(x, m);
        			}
        			max=Math.max(max, map.get(x).get(y));                    
                }
                res=Math.max(max+samepoint,res);
            }
        }
        return res;
    }
    private int gcd(int a, int b){
        if(b==0)
            return a;
        return gcd(b, a%b);
    }
}

  

以上是关于149. Max Points on a Line的主要内容,如果未能解决你的问题,请参考以下文章

149. Max Points on a Line

leetcode149 Max Points on a Line

149. Max Points on a Line

149 Max Points on a Line 直线上最多的点数

149. Max Points on a Line

leetcode149- Max Points on a Line- hard