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.

 

/**
 * 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) {
        HashMap<Double, Integer> slopeMap = new HashMap<Double, Integer>();
        Integer result = 0;
        if(points == null || points.length == 0) return result;
        for(int i = 0; i < points.length; i ++){
            slopeMap.clear();
            Integer sameValue = 0;
            for(int j = i; j < points.length; j ++){
            //need to start from i, or should return result + 1. since we don't count point i itself
                if(points[i].x == points[j].x && points[i].y == points[j].y){
                    sameValue ++;
                }else{
                    Double slope = slopeForTwoPoint(points[i], points[j]);
                    if(slopeMap.containsKey(slope)){
                        slopeMap.put(slope, slopeMap.get(slope) + 1);
                    }else{
                        slopeMap.put(slope, 1);
                    }
                }
            }
            Iterator it = slopeMap.values().iterator();
            while(it.hasNext()){
                Integer val = (Integer)it.next();
                result = Math.max(val + sameValue, result);
            }
            
            //if all the points are same points
            result = Math.max(sameValue, result);
        }
        return result;
    }
    
    public Double slopeForTwoPoint(Point a, Point b){
    //hashmap can have null as key, so take use of this feature.
        if(a.x == b.x) return null;
    //a.y == b.y case
        else if(a.y == b.y) return (double)0;
        else return ((double)a.y - (double)b.y) / ((double)a.x - (double)b.x);
    }
}

 

posted on 2013-11-25 05:47  Step-BY-Step  阅读(151)  评论(0编辑  收藏  举报

导航