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, Integer>来存斜率,但是如果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<String, Integer> map = new HashMap<String, Integer>();
            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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值