Max Points on a Line

/**

 * Definition for a point.

 * class Point {

 *     int x;

 *     int y;

 *     Point() { x = 0; y = 0; }

 *     Point(int a, int b) { x = a; y = b; }

 * }

 */

public class Solution {

    public int maxPoints(Point[] points) {

        // ref http://www.cnblogs.com/springfor/p/3896120.html

        // ref http://blog.csdn.net/linhuanmars/article/details/21060933

        if(points==null || points.length==0) return 0;

        if(points.length==1) return 1;

        int max = 1;

        double slope = 0.0;

        for(int i=0;i<points.length-1;i++){

            int local = 1;

            HashMap<Double, Integer> hm = new HashMap<Double, Integer>();

            int same = 0;             // points that are on the same position of i

            for(int j=i+1;j<points.length;j++){

                if(points[i].x ==points[j].x &&points[i].y ==points[j].y){

                    same++;

                    continue;

                }else if(points[i].y ==points[j].y){

                    slope  =0.0;

                }

                else if (points[i].x ==points[j].x){

                    slope  =(double) Integer.MAX_VALUE; 

                }

                else

                    slope = (double)(points[i].y - points[j].y)/(points[i].x - points[j].x); 

                if(hm.containsKey(slope)){

                    hm.put(slope,hm.get(slope)+1);

                }else{

                    hm.put(slope,2);

                }

            }

            for(Integer v: hm.values()){

                local = Math.max(local, v);

            }

            local += same;

            max = Math.max(max,local);

        }

        return max;

    }

}

 

你可能感兴趣的:(poi)