`

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.

Solution:

public int maxPoints(Point[] points) {
        if(points.length < 3) return points.length;
        int result = 2; // at least 2 points on a line
        Map<Double, Integer> map = new HashMap<>();
        for(Point p:points) {
            map.clear();
            int duplicate = 1; // [(1,1),(1,1),(2,2),(2,2)] -> 4
            map.put(Double.MIN_VALUE, 0); // for special case: [(1,1),(1,1),(1,1)], no slope will be put to map
            for(Point q:points) {
                if(p == q) continue;
                if(p.x == q.x && p.y == q.y) {
                    duplicate++;
                    continue;
                }
                double slope = (p.x == q.x) ? Double.MAX_VALUE : (p.y-q.y)/(double)(p.x-q.x);
                Integer cnt = map.get(slope);
                if(cnt == null) cnt = 0;
                map.put(slope, cnt+1);
            }
            for(Integer cnt:map.values()) {
                result = Math.max(result, cnt+duplicate);
            }
        }
        return result;
    }

 

重构了下代码:

public int maxPoints(Point[] points) {
    if(points == null) return 0;
    int maxNum = 0;
    Map<Double, Integer> map = new HashMap<>();
    for(Point p:points) {
        int dup = 1;
        map.clear();
        for(Point q:points) {
            if(p == q) continue;
            if(p.x == q.x && p.y == q.y) {
                dup++; continue;
            }
            double slope = slope(p, q);
            Integer cnt = map.get(slope);
            if(cnt == null) cnt = 0;
            map.put(slope, cnt+1);
        }
        // for special case: [(1,1),(1,1),(1,1)], no slope will be put to map
        if(map.size() == 0) return points.length; 
        for(int cnt:map.values()) {
            maxNum = Math.max(maxNum, cnt+dup);
        }
    }
    return maxNum;
}

private double slope(Point p1, Point p2) {
    if(p1.x == p2.x) return Double.MAX_VALUE;
    return (p2.y-p1.y)/((double)(p2.x-p1.x));
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics