LeeCode(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.

分析如下:

思路比较直接,对其中某一个点i, 找到点i和剩下的所有n - 1个点构成的斜率。如果在这n - 1个斜率中,能够找到这样一个值,这个出现次数最多,那么就可以认为,取得这些值的点就是能够找到的可以和i在同一个直线上的所有点。

把上面的事情,对所有的点都做一遍,这样就能找到一个最大的点集合,在同一个直线上。

所以用一个hash来统计, key = 斜率, value = 能够和i点取得key的其他点。

坑在,由于用了Float作为key,所以Float里面对0的表达方式有 - 0.0 和0.0两种,所以就造成了两个为0的斜率直线被认为斜率不等。

解决方式比较巧妙,给所有斜率加上0.0即可。


我的代码:

//ERROR: Input: [[2,3],[3,3],[-5,3]]  Output : 2 Expected : 3 (slope = -0.0, vs slop = 0.0 are incorrectly viewed as different)
public class Solution {
    public int maxPoints(Point[] points) {
        if (points == null) {
            return 0;
        }
        if (points.length <= 2) {
            return points.length;
        }
        int global = 0;
        for (int i = 0; i < points.length; ++i) {
            Map<Double, Integer> map = new HashMap<Double, Integer> ();
            double slope = 0.0;
            int samePoint = 0;
            int verticalPoint = 0;
            int local = 1;
            for (int j = i + 1; j < points.length; ++j) {
                if (points[i].x == points[j].x && points[i].y == points[j].y) {
                    ++samePoint;
                } else{
                    if (points[i].x == points[j].x) {
                        ++verticalPoint;
                    } else {
                        //ERROR5: 加上0.0是因为Double representaion会把0.0和-0.0看成不同的数,所以加上0.0来消除这个问题
                        slope = 0.0 + (points[i].y - points[j].y)  * 1.0 / (points[i].x - points[j].x); 
                        if (!map.containsKey(slope)) {
                            map.put(slope, 2);
                        } else {
                            map.put(slope, map.get(slope) + 1);
                        }
                        local = Math.max(local, map.get(slope));
                    }
                }
            }
            local = Math.max(samePoint + 1 + verticalPoint , samePoint + local);
            global = Math.max(local, global);            
        }
        return global;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值