149.直线上最多的点数

题解

java的hashmap的double为key时,有精度问题 转换为求公约数的String key。


class Solution {
    public int maxPoints(int[][] points) { //牛b我只说一次
        HashMap<String, Integer> map = new HashMap<>();
        int res = 0; int same = 1; int parallel = 1;
        for (int i = 0; i < points.length; ++i){
            same = 1; parallel = 1;
            for (int j = i + 1; j < points.length;++j){
                if (points[i][1] == points[j][1]){
                    ++parallel;
                    if (points[i][0] == points[j][0]){
                        ++same;
                    }
                }else{
                    String key = computeKey(points[i][0] - points[j][0] , points[i][1] - points[j][1]);
                    map.put(key, map.getOrDefault(key, 0) == 0 ? 1:map.get(key) + 1);
                }
            }
            res = Math.max(parallel, res);
            for (Integer item : map.values()){
                res = Math.max(item + same, res);
            }
            map.clear();
        }

        return res;
    }

    private String computeKey(int dx, int dy) {
        int gcd = computeGcd(dx, dy);
        return dx / gcd + "_" + dy / gcd;
    }
    private int computeGcd(int p, int q){
        if (q == 0) return p;
        int r = p % q;
        return computeGcd(q ,r);
    }
}
posted @ 2021-01-02 18:09  backTraced  阅读(50)  评论(0编辑  收藏  举报