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.

这道题应该注意只要是在一条直线上就算。第一反应是用HashMap来存斜率,但是如果double精确到小数点后好多位之后就趋于相等,key值就相等了,所以一般不要用double作key。这里可以用最大公约数gcd来吧斜率的分子分母化简作string的key。如果j想初始化为i+1,就在外循环再遍历一波map找最大。代码如下:

/**
 * 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) {
        if (points == null) {
            return 0;
        }
        if (points.length <= 2) {
            return points.length;
        }
        int res = 0;
        for (int i = 0; i < points.length; i ++) {
            int same = 0;
            int sameX = 1;
            HashMap map = new HashMap();
            for (int j = 0; j < points.length; j ++) {
                if (i != j) {
                    if ((points[i].x == points[j].x) && (points[i].y == points[j].y)) {
                        same ++;
                    }
                    if (points[i].x == points[j].x) {
                        sameX ++;
                        continue;
                    }
                    int a = points[i].y - points[j].y;
                    int b = points[i].x - points[j].x;
                    int gcd = findGCD(a, b);
                    String k = (a / gcd) + "" + (b / gcd);
                    if (map.containsKey(k)) {
                        map.put(k, map.get(k) + 1);
                    } else {
                        map.put(k, 2);
                    }
                    res = Math.max(res, map.get(k) + same);
                }
            }
            res = Math.max(res, sameX);
        }
        return res;
    }
    
    private int findGCD(int a, int b) {
        if (a == 0) {
            return b;
        }
        return findGCD(b % a, a);
    }
}

你可能感兴趣的:(LeetCode,Hash,Table,Math,LeetCode,Hash,Table,Math,Max,Points,on,a,Line)